From 55f294bb3387fa0ea22eb59ab8084ae24fba77d4 Mon Sep 17 00:00:00 2001 From: kristoffer Date: Wed, 15 Apr 2026 10:59:47 +0200 Subject: [PATCH 01/24] Added map-stops and basic endpoints --- .../backend/iam/api/MapStopsController.kt | 70 +++++++++++++++++++ .../backend/iam/application/MapService.kt | 21 ++++++ .../idi/idatt/backend/iam/domain/MapStops.kt | 33 +++++++++ .../iam/infrastructure/MapStopsRepository.kt | 17 +++++ 4 files changed, 141 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/api/MapStopsController.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/MapService.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/MapStops.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/api/MapStopsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/api/MapStopsController.kt new file mode 100644 index 00000000..7aab47e2 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/api/MapStopsController.kt @@ -0,0 +1,70 @@ +package edu.ntnu.idi.idatt.backend.iam.api + +import edu.ntnu.idi.idatt.backend.iam.application.MapService +import edu.ntnu.idi.idatt.backend.iam.domain.MapStops +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController + +class MapStopsController { + + @RestController + @RequestMapping("/api/map-stops") + class MapStopsController(private val mapService: MapService) { + + @GetMapping + fun getAllMapStops(): ResponseEntity> { + return ResponseEntity.ok( + mapService.getAllMapStops().map {it.toResponse()} + ) + } + + @GetMapping("/{slug}") + fun getMapStop(@PathVariable slug: String): ResponseEntity { + return ResponseEntity.ok( + mapService.getMapStopByTitle(slug)?.toResponse() + ?: throw NoSuchElementException("No map stop found for $slug") + )} + } +} + +/** + * Response payload for a single map stop. + * + * @property id unique identifier of the map stop + * @property slug short reference code for the stop + * @property title display title of the stop + * @property slug URL-safe kebab-case identifier derived from the title + * @property description full description text of the stop + * @property category category the stop belongs to + * @property displayOrder position of the stop in the ordered map list + * @property isFinalBoss whether this stop is the final boss stop + * @property isActive whether this stop is currently visible + */ +data class MapStopResponse( + val id: Long, + val slug: String?, + val title: String?, + val description: String?, + val category: String?, + val displayOrder: Int?, + val isFinalBoss: Boolean?, + val isActive: Boolean?, +) + +/** + * Converts a [MapStop] domain entity to the public [MapStopResponse] payload. + */ +private fun MapStops.toResponse(): MapStopResponse = + MapStopResponse( + id = id!!, + slug = slug, + title = title, + description = description, + category = category, + displayOrder = displayOrder, + isFinalBoss = isFinalBoss, + isActive = isActive, + ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/MapService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/MapService.kt new file mode 100644 index 00000000..d9c28eea --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/MapService.kt @@ -0,0 +1,21 @@ +package edu.ntnu.idi.idatt.backend.iam.application + +import edu.ntnu.idi.idatt.backend.iam.domain.MapStops +import edu.ntnu.idi.idatt.backend.iam.infrastructure.MapStopsRepository +import org.springframework.stereotype.Service + +@Service +class MapService( + private val mapStopsrepository: MapStopsRepository +) { + + fun getAllMapStops(): List { + return mapStopsrepository.findAll() + } + + fun getMapStopByTitle (title: String): MapStops? { + val title = title.replace("-", " ") + return mapStopsrepository.findByTitleIgnoreCase(title) + ?: throw NoSuchElementException("No map stop found for $title") + } +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/MapStops.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/MapStops.kt new file mode 100644 index 00000000..4132a254 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/MapStops.kt @@ -0,0 +1,33 @@ +package edu.ntnu.idi.idatt.backend.iam.domain + +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.Table + +/** + * A map-stop representation + */ +@Entity +@Table(name = "map_stops") +class MapStops { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long? = null + @Column(length = 255) + var slug: String? = null + @Column(length = 255) + var title: String? = null + @Column() + var description: String? = null + @Column(length = 255) + var category: String? = null + @Column(name = "display_order") + var displayOrder: Int? = null + @Column(name="is_final_boss") + var isFinalBoss: Boolean? = false + @Column(name = "is_active") + var isActive: Boolean? = false +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt new file mode 100644 index 00000000..632271d9 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt @@ -0,0 +1,17 @@ +package edu.ntnu.idi.idatt.backend.iam.infrastructure + +import edu.ntnu.idi.idatt.backend.iam.domain.MapStops +import org.springframework.data.jpa.repository.JpaRepository + +/** + * Repository for loading map-stops. + */ +interface MapStopsRepository : JpaRepository { + /** + * Finds a map-stop by title without case sensitivity. + * + * @param title the title of the map stop + * @return matching map-stop + */ + fun findBySlugIgnoreCase(slug: String): MapStops? +} \ No newline at end of file From ca77736509b2bb4586397e0ce498bd85b97c2a81 Mon Sep 17 00:00:00 2001 From: kristoffer Date: Wed, 15 Apr 2026 11:15:22 +0200 Subject: [PATCH 02/24] refactored for domain structure --- .../idatt/backend/iam/infrastructure/MapStopsRepository.kt | 2 +- .../backend/{iam => mapStops}/api/MapStopsController.kt | 6 +++--- .../backend/{iam => mapStops}/application/MapService.kt | 4 ++-- .../idi/idatt/backend/{iam => mapStops}/domain/MapStops.kt | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{iam => mapStops}/api/MapStopsController.kt (92%) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{iam => mapStops}/application/MapService.kt (82%) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{iam => mapStops}/domain/MapStops.kt (94%) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt index 632271d9..f1e85d7b 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt @@ -1,6 +1,6 @@ package edu.ntnu.idi.idatt.backend.iam.infrastructure -import edu.ntnu.idi.idatt.backend.iam.domain.MapStops +import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops import org.springframework.data.jpa.repository.JpaRepository /** diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/api/MapStopsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt similarity index 92% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/api/MapStopsController.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt index 7aab47e2..fcbf3e77 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/api/MapStopsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt @@ -1,7 +1,7 @@ -package edu.ntnu.idi.idatt.backend.iam.api +package edu.ntnu.idi.idatt.backend.mapStops.api -import edu.ntnu.idi.idatt.backend.iam.application.MapService -import edu.ntnu.idi.idatt.backend.iam.domain.MapStops +import edu.ntnu.idi.idatt.backend.mapStops.application.MapService +import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/MapService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapService.kt similarity index 82% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/MapService.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapService.kt index d9c28eea..c4156aaf 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/MapService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapService.kt @@ -1,7 +1,7 @@ -package edu.ntnu.idi.idatt.backend.iam.application +package edu.ntnu.idi.idatt.backend.mapStops.application -import edu.ntnu.idi.idatt.backend.iam.domain.MapStops import edu.ntnu.idi.idatt.backend.iam.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops import org.springframework.stereotype.Service @Service diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/MapStops.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/domain/MapStops.kt similarity index 94% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/MapStops.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/domain/MapStops.kt index 4132a254..737014c2 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/MapStops.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/domain/MapStops.kt @@ -1,4 +1,4 @@ -package edu.ntnu.idi.idatt.backend.iam.domain +package edu.ntnu.idi.idatt.backend.mapStops.domain import jakarta.persistence.Column import jakarta.persistence.Entity @@ -30,4 +30,4 @@ class MapStops { var isFinalBoss: Boolean? = false @Column(name = "is_active") var isActive: Boolean? = false -} +} \ No newline at end of file From cc547f45a30b429142f1c2250351b502045a6de4 Mon Sep 17 00:00:00 2001 From: kristoffer Date: Wed, 15 Apr 2026 11:24:31 +0200 Subject: [PATCH 03/24] Added javadoc and better names --- .../mapStops/api/MapStopsController.kt | 51 ++++++++++++------- .../{MapService.kt => MapStopService.kt} | 18 +++++-- .../infrastructure/MapStopsRepository.kt | 2 +- 3 files changed, 48 insertions(+), 23 deletions(-) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/{MapService.kt => MapStopService.kt} (57%) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{iam => mapStops}/infrastructure/MapStopsRepository.kt (88%) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt index fcbf3e77..39f6c0ee 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt @@ -1,6 +1,6 @@ package edu.ntnu.idi.idatt.backend.mapStops.api -import edu.ntnu.idi.idatt.backend.mapStops.application.MapService +import edu.ntnu.idi.idatt.backend.mapStops.application.MapStopService import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping @@ -8,28 +8,41 @@ import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController -class MapStopsController { - - @RestController - @RequestMapping("/api/map-stops") - class MapStopsController(private val mapService: MapService) { +/** + * Exposes HTTP endpoints for map-stops. + * + * @property mapStopService application service that handles the mapstops + */ - @GetMapping - fun getAllMapStops(): ResponseEntity> { - return ResponseEntity.ok( - mapService.getAllMapStops().map {it.toResponse()} - ) - } +@RestController +@RequestMapping("/api/map-stops") +class MapStopsController(private val mapStopService: MapStopService) { - @GetMapping("/{slug}") - fun getMapStop(@PathVariable slug: String): ResponseEntity { - return ResponseEntity.ok( - mapService.getMapStopByTitle(slug)?.toResponse() - ?: throw NoSuchElementException("No map stop found for $slug") - )} + /** + * Finds all map stops. Used in the map. + * @return List of mapStopResponses + */ + @GetMapping + fun getAllMapStops(): ResponseEntity> { + return ResponseEntity.ok( + mapStopService.getAllMapStops().map {it.toResponse()} + ) } + + /** + * Returns a specific map stop. + * + * @return A mapStopResponse + */ + @GetMapping("/{slug}") + fun getMapStop(@PathVariable slug: String): ResponseEntity { + return ResponseEntity.ok( + mapStopService.getMapStopByTitle(slug)?.toResponse() + ?: throw NoSuchElementException("No map stop found for $slug") + )} } + /** * Response payload for a single map stop. * @@ -55,7 +68,7 @@ data class MapStopResponse( ) /** - * Converts a [MapStop] domain entity to the public [MapStopResponse] payload. + * Converts a [MapStops] domain entity to the public [MapStopResponse] payload. */ private fun MapStops.toResponse(): MapStopResponse = MapStopResponse( diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapStopService.kt similarity index 57% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapService.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapStopService.kt index c4156aaf..c4cb8519 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapStopService.kt @@ -1,21 +1,33 @@ package edu.ntnu.idi.idatt.backend.mapStops.application -import edu.ntnu.idi.idatt.backend.iam.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.mapStops.infrastructure.MapStopsRepository import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops import org.springframework.stereotype.Service +/** + * Service for mapStops. + */ @Service -class MapService( +class MapStopService( private val mapStopsrepository: MapStopsRepository ) { + /** + * Finds all map stops. + * + * @return List of [MapStops] + */ fun getAllMapStops(): List { return mapStopsrepository.findAll() } + /** + * Finds a specific map stop from the slug. + * @return A [MapStops] + */ fun getMapStopByTitle (title: String): MapStops? { val title = title.replace("-", " ") - return mapStopsrepository.findByTitleIgnoreCase(title) + return mapStopsrepository.findBySlugIgnoreCase(title) ?: throw NoSuchElementException("No map stop found for $title") } } \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/infrastructure/MapStopsRepository.kt similarity index 88% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/infrastructure/MapStopsRepository.kt index f1e85d7b..61cc1e77 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/MapStopsRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/infrastructure/MapStopsRepository.kt @@ -1,4 +1,4 @@ -package edu.ntnu.idi.idatt.backend.iam.infrastructure +package edu.ntnu.idi.idatt.backend.mapStops.infrastructure import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops import org.springframework.data.jpa.repository.JpaRepository From 633a538acd4b4ec18727dc0ecb042144a3ba18c3 Mon Sep 17 00:00:00 2001 From: kristoffer Date: Wed, 15 Apr 2026 13:36:00 +0200 Subject: [PATCH 04/24] Changed structure --- .../backend/{ => game}/mapStops/api/MapStopsController.kt | 6 +++--- .../{ => game}/mapStops/application/MapStopService.kt | 6 +++--- .../idatt/backend/{ => game}/mapStops/domain/MapStops.kt | 2 +- .../mapStops/infrastructure/MapStopsRepository.kt | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{ => game}/mapStops/api/MapStopsController.kt (92%) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{ => game}/mapStops/application/MapStopService.kt (76%) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{ => game}/mapStops/domain/MapStops.kt (93%) rename src/main/kotlin/edu/ntnu/idi/idatt/backend/{ => game}/mapStops/infrastructure/MapStopsRepository.kt (75%) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt similarity index 92% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt index 39f6c0ee..d2147f0f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/api/MapStopsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt @@ -1,7 +1,7 @@ -package edu.ntnu.idi.idatt.backend.mapStops.api +package edu.ntnu.idi.idatt.backend.game.mapStops.api -import edu.ntnu.idi.idatt.backend.mapStops.application.MapStopService -import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.application.MapStopService +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapStopService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt similarity index 76% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapStopService.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt index c4cb8519..5154bccf 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/application/MapStopService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt @@ -1,7 +1,7 @@ -package edu.ntnu.idi.idatt.backend.mapStops.application +package edu.ntnu.idi.idatt.backend.game.mapStops.application -import edu.ntnu.idi.idatt.backend.mapStops.infrastructure.MapStopsRepository -import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops import org.springframework.stereotype.Service /** diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/domain/MapStops.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt similarity index 93% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/domain/MapStops.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt index 737014c2..e6116b98 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/domain/MapStops.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt @@ -1,4 +1,4 @@ -package edu.ntnu.idi.idatt.backend.mapStops.domain +package edu.ntnu.idi.idatt.backend.game.mapStops.domain import jakarta.persistence.Column import jakarta.persistence.Entity diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/infrastructure/MapStopsRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt similarity index 75% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/infrastructure/MapStopsRepository.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt index 61cc1e77..0962b131 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/mapStops/infrastructure/MapStopsRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt @@ -1,6 +1,6 @@ -package edu.ntnu.idi.idatt.backend.mapStops.infrastructure +package edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure -import edu.ntnu.idi.idatt.backend.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops import org.springframework.data.jpa.repository.JpaRepository /** From 03504905181b562057fa26526e4a7b6f7fb0ccec Mon Sep 17 00:00:00 2001 From: kristoffer Date: Thu, 16 Apr 2026 09:52:47 +0200 Subject: [PATCH 05/24] finished adding mapStops and PupilStopProgress implementations --- .../backend/classroom/domain/Classroom.kt | 15 + .../game/mapStops/api/MapStopApiMappings.kt | 49 +++ .../mapStops/api/MapStopOverviewResponse.kt | 28 ++ .../game/mapStops/api/MapStopsController.kt | 98 ++---- .../api/PupilStopProgressController.kt | 89 +++++ .../game/mapStops/api/StopProgressResponse.kt | 27 ++ .../mapStops/api/UpdateStopProgressRequest.kt | 19 ++ .../mapStops/application/MapStopService.kt | 134 +++++++- .../PupilProgressSeedingService.kt | 68 ++++ .../application/PupilStopProgressService.kt | 100 ++++++ .../application/UpdateStopProgressCommand.kt | 18 ++ .../backend/game/mapStops/domain/MapStops.kt | 4 +- .../game/mapStops/domain/PupilStopProgress.kt | 73 +++++ .../infrastructure/MapStopsRepository.kt | 14 +- .../PupilStopProgressRepository.kt | 21 ++ .../db/migration/V5__create_classroom.sql | 3 + .../V6__create_user_settings_table.sql | 33 ++ .../game/mapStops/MapStopServiceTests.kt | 278 ++++++++++++++++ .../PupilProgressSeedingServiceTests.kt | 163 ++++++++++ .../mapStops/PupilStopProgressServiceTests.kt | 304 ++++++++++++++++++ 20 files changed, 1451 insertions(+), 87 deletions(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt create mode 100644 src/main/resources/db/migration/V5__create_classroom.sql create mode 100644 src/main/resources/db/migration/V6__create_user_settings_table.sql create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt new file mode 100644 index 00000000..495f210d --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt @@ -0,0 +1,15 @@ +package edu.ntnu.idi.idatt.backend.classroom.domain + +import jakarta.persistence.Entity +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.Table + +@Entity +@Table(name = "classrooms") +class Classroom { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long? = null +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt new file mode 100644 index 00000000..82e38a13 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt @@ -0,0 +1,49 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.api + +import edu.ntnu.idi.idatt.backend.game.mapStops.application.MapStopOverviewEntry +import edu.ntnu.idi.idatt.backend.game.mapStops.application.UpdateStopProgressCommand +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress + +/** + * Converts a [PupilStopProgress] domain entity to the public [StopProgressResponse] payload. + */ +fun PupilStopProgress.toStopProgressResponse(): StopProgressResponse = + StopProgressResponse( + pupilUserId = id.pupilUserId, + classroomId = id.classroomId, + stopId = id.stopId, + status = status, + currentTaskId = currentTaskId, + bestScore = bestScore, + medalAwarded = medalAwarded, + completedAt = completedAt, + ) + +/** + * Converts an [UpdateStopProgressRequest] HTTP payload to the [UpdateStopProgressCommand] + * consumed by the application layer. + */ +fun UpdateStopProgressRequest.toCommand(): UpdateStopProgressCommand = + UpdateStopProgressCommand( + status = status, + currentTaskId = currentTaskId, + bestScore = bestScore, + medalAwarded = medalAwarded, + ) + +/** + * Converts a [MapStopOverviewEntry] application result to the public [MapStopOverviewResponse] + * payload. + */ +fun MapStopOverviewEntry.toResponse(): MapStopOverviewResponse = + MapStopOverviewResponse( + stopId = stopId, + slug = slug, + title = title, + category = category, + displayOrder = displayOrder, + isFinalBoss = isFinalBoss, + status = status, + stars = stars, + medalAwarded = medalAwarded, + ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt new file mode 100644 index 00000000..547a2e01 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt @@ -0,0 +1,28 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.api + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus + +/** + * Response payload for a single map stop enriched with the pupil's progress. + * + * @property stopId unique identifier of the map stop + * @property slug URL-safe kebab-case identifier + * @property title display title of the stop + * @property category category the stop belongs to + * @property displayOrder position of the stop in the ordered map list + * @property isFinalBoss whether this stop is the final boss stop + * @property status current progress status for the authenticated pupil + * @property stars number of stars earned, derived from bestScore vs maxScore + * @property medalAwarded whether a medal has been awarded for this stop + */ +data class MapStopOverviewResponse( + val stopId: Long, + val slug: String?, + val title: String?, + val category: String?, + val displayOrder: Int, + val isFinalBoss: Boolean, + val status: StopProgressStatus, + val stars: Int, + val medalAwarded: Boolean, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt index d2147f0f..032406be 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt @@ -1,83 +1,55 @@ package edu.ntnu.idi.idatt.backend.game.mapStops.api import edu.ntnu.idi.idatt.backend.game.mapStops.application.MapStopService -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops -import org.springframework.http.ResponseEntity +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController /** - * Exposes HTTP endpoints for map-stops. + * Exposes endpoints for retrieving map stops and the aggregated map overview for a pupil. * - * @property mapStopService application service that handles the mapstops + * @property mapStopService application service that handles map stop lookups and overview aggregation */ - @RestController -@RequestMapping("/api/map-stops") -class MapStopsController(private val mapStopService: MapStopService) { - +@RequestMapping("/api/v1/classrooms/{classroomId}/map-stops") +class MapStopsController( + private val mapStopService: MapStopService, +) { /** - * Finds all map stops. Used in the map. - * @return List of mapStopResponses + * Returns all active map stops enriched with the pupil's progress, stars, and lock state, + * sorted by display order. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @param classroomId classroom to scope the progress lookup to + * @return sorted list of stops with progress state for the authenticated pupil */ @GetMapping - fun getAllMapStops(): ResponseEntity> { - return ResponseEntity.ok( - mapStopService.getAllMapStops().map {it.toResponse()} - ) - } + fun getMapOverview( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + ): List = + mapStopService + .getMapOverview(currentUser.subject.toLong(), classroomId) + .map { it.toResponse() } /** - * Returns a specific map stop. + * Returns a single active map stop by its URL slug, enriched with the pupil's progress. * - * @return A mapStopResponse + * @param currentUser authenticated principal resolved from the JWT access token + * @param classroomId classroom to scope the progress lookup to + * @param slug kebab-case slug of the map stop title + * @return map stop matching the given slug with progress state for the authenticated pupil */ @GetMapping("/{slug}") - fun getMapStop(@PathVariable slug: String): ResponseEntity { - return ResponseEntity.ok( - mapStopService.getMapStopByTitle(slug)?.toResponse() - ?: throw NoSuchElementException("No map stop found for $slug") - )} -} - - -/** - * Response payload for a single map stop. - * - * @property id unique identifier of the map stop - * @property slug short reference code for the stop - * @property title display title of the stop - * @property slug URL-safe kebab-case identifier derived from the title - * @property description full description text of the stop - * @property category category the stop belongs to - * @property displayOrder position of the stop in the ordered map list - * @property isFinalBoss whether this stop is the final boss stop - * @property isActive whether this stop is currently visible - */ -data class MapStopResponse( - val id: Long, - val slug: String?, - val title: String?, - val description: String?, - val category: String?, - val displayOrder: Int?, - val isFinalBoss: Boolean?, - val isActive: Boolean?, -) - -/** - * Converts a [MapStops] domain entity to the public [MapStopResponse] payload. - */ -private fun MapStops.toResponse(): MapStopResponse = - MapStopResponse( - id = id!!, - slug = slug, - title = title, - description = description, - category = category, - displayOrder = displayOrder, - isFinalBoss = isFinalBoss, - isActive = isActive, - ) \ No newline at end of file + fun getMapStopBySlug( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + @PathVariable slug: String, + ): MapStopOverviewResponse = + mapStopService + .getMapStopOverviewBySlug(currentUser.subject.toLong(), classroomId, slug) + .toResponse() +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt new file mode 100644 index 00000000..5aa79153 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt @@ -0,0 +1,89 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.api + +import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilStopProgressService +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import jakarta.validation.Valid +import org.springframework.security.access.prepost.PreAuthorize +import org.springframework.security.core.annotation.AuthenticationPrincipal +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PatchMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController + +/** + * Exposes endpoints for reading and updating a pupil's progress across map stops. + * + * @property progressService application service that handles progress lookup and state transitions + */ +@RestController +@RequestMapping("/api/v1/classrooms/{classroomId}/pupils/{pupilUserId}/stop-progress") +class PupilStopProgressController( + private val progressService: PupilStopProgressService, +) { + /** + * Returns all stop progress records for a pupil in a classroom. + * Accessible by the pupil themselves or a teacher. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @param classroomId classroom to scope the lookup to + * @param pupilUserId pupil whose progress to retrieve + * @return list of progress records for all stops in the classroom + */ + @GetMapping + @PreAuthorize("hasRole('TEACHER') or #pupilUserId == authentication.principal.subjectAsLong") + fun getAllProgress( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + @PathVariable pupilUserId: Long, + ): List = + progressService + .getProgressForPupil(pupilUserId, classroomId) + .map { it.toStopProgressResponse() } + + /** + * Returns progress for a single stop for a pupil in a classroom. + * Accessible by the pupil themselves or a teacher. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @param classroomId classroom to scope the lookup to + * @param pupilUserId pupil whose progress to retrieve + * @param stopId map stop to retrieve progress for + * @return progress record for the given stop + */ + @GetMapping("/{stopId}") + @PreAuthorize("hasRole('TEACHER') or #pupilUserId == authentication.principal.subjectAsLong") + fun getStopProgress( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + @PathVariable pupilUserId: Long, + @PathVariable stopId: Long, + ): StopProgressResponse = + progressService + .getProgressForStop(pupilUserId, classroomId, stopId) + .toStopProgressResponse() + + /** + * Updates progress for a single stop. Only the pupil themselves may update their own progress. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @param classroomId classroom to scope the update to + * @param pupilUserId pupil whose progress to update + * @param stopId map stop to update progress for + * @param request progress update payload + * @return updated progress record + */ + @PatchMapping("/{stopId}") + @PreAuthorize("#pupilUserId == authentication.principal.subjectAsLong") + fun updateStopProgress( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + @PathVariable pupilUserId: Long, + @PathVariable stopId: Long, + @Valid @RequestBody request: UpdateStopProgressRequest, + ): StopProgressResponse = + progressService + .updateProgress(pupilUserId, classroomId, stopId, request.toCommand()) + .toStopProgressResponse() +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt new file mode 100644 index 00000000..93830861 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt @@ -0,0 +1,27 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.api + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import java.time.Instant + +/** + * Response payload for a pupil's progress on a single map stop. + * + * @property pupilUserId pupil this progress record belongs to + * @property classroomId classroom this progress is scoped to + * @property stopId map stop this progress tracks + * @property status current progress status + * @property currentTaskId current task the pupil is on, or null + * @property bestScore highest score achieved at this stop + * @property medalAwarded whether a medal has been awarded + * @property completedAt timestamp of completion, or null if not yet completed + */ +data class StopProgressResponse( + val pupilUserId: Long, + val classroomId: Long, + val stopId: Long, + val status: StopProgressStatus, + val currentTaskId: Long?, + val bestScore: Int, + val medalAwarded: Boolean, + val completedAt: Instant?, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt new file mode 100644 index 00000000..4d12bbfc --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt @@ -0,0 +1,19 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.api + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import jakarta.validation.constraints.Min + +/** + * Request payload for updating a pupil's progress on a single map stop. + * + * @property status new status to transition to, must follow valid state machine transitions + * @property currentTaskId current task the pupil is working on within this stop + * @property bestScore pupil's best score, only persisted if higher than the existing value + * @property medalAwarded whether a medal has been awarded for this stop + */ +data class UpdateStopProgressRequest( + val status: StopProgressStatus?, + val currentTaskId: Long?, + @field:Min(0) val bestScore: Int?, + val medalAwarded: Boolean?, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt index 5154bccf..6546847d 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt @@ -1,33 +1,139 @@ package edu.ntnu.idi.idatt.backend.game.mapStops.application -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository +import org.springframework.http.HttpStatus import org.springframework.stereotype.Service +import org.springframework.web.server.ResponseStatusException /** - * Service for mapStops. + * Application service that handles map stop lookups and map overview aggregation. + * + * @property mapStopsRepository JPA repository for map stop records + * @property pupilStopProgressRepository JPA repository for pupil stop progress records */ @Service class MapStopService( - private val mapStopsrepository: MapStopsRepository + private val mapStopsRepository: MapStopsRepository, + private val pupilStopProgressRepository: PupilStopProgressRepository, ) { + /** + * Returns all active map stops sorted by display order. + * + * @return sorted list of active map stops + */ + fun getAllMapStops(): List = + mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc() /** - * Finds all map stops. + * Returns a single active map stop by its URL slug. * - * @return List of [MapStops] + * @param slug kebab-case slug to look up + * @return matching map stop + * @throws ResponseStatusException 404 if no stop matches the slug */ - fun getAllMapStops(): List { - return mapStopsrepository.findAll() + fun getMapStopBySlug(slug: String): MapStops { + val normalized = slug.replace("-", " ") + return mapStopsRepository.findBySlugIgnoreCase(normalized) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "No map stop found for slug: $slug") } /** - * Finds a specific map stop from the slug. - * @return A [MapStops] + * Returns all active map stops enriched with the pupil's progress, stars, and lock state, + * sorted by display order. + * + * @param pupilUserId pupil to retrieve progress for + * @param classroomId classroom to scope the progress lookup to + * @return sorted list of stops with progress state for the pupil */ - fun getMapStopByTitle (title: String): MapStops? { - val title = title.replace("-", " ") - return mapStopsrepository.findBySlugIgnoreCase(title) - ?: throw NoSuchElementException("No map stop found for $title") + fun getMapOverview(pupilUserId: Long, classroomId: Long): List { + val stops = mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc() + val progressByStopId = pupilStopProgressRepository + .findAllById_PupilUserIdAndId_ClassroomId(pupilUserId, classroomId) + .associateBy { it.id.stopId } + + return stops.mapNotNull { stop -> + val stopId = stop.id ?: return@mapNotNull null + val progress = progressByStopId[stop.id!!] + MapStopOverviewEntry( + stopId = stopId, + slug = stop.slug, + title = stop.title, + category = stop.category, + displayOrder = stop.displayOrder ?: 0, + isFinalBoss = stop.isFinalBoss ?: false, + status = progress?.status ?: StopProgressStatus.LOCKED, + stars = progress?.let { computeStars(it.bestScore, stop.maxScore ?: 0) } ?: 0, + medalAwarded = progress?.medalAwarded ?: false, + ) + } } -} \ No newline at end of file + + /** + * Returns a single active map stop by its URL slug, enriched with the pupil's progress. + * + * @param pupilUserId pupil to retrieve progress for + * @param classroomId classroom to scope the progress lookup to + * @param slug kebab-case slug to look up + * @return map stop matching the given slug with progress state for the pupil + * @throws ResponseStatusException 404 if no stop matches the slug + */ + fun getMapStopOverviewBySlug(pupilUserId: Long, classroomId: Long, slug: String): MapStopOverviewEntry { + val stop = getMapStopBySlug(slug) + val stopId = stop.id + ?: throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Map stop has no id") + + val progress = pupilStopProgressRepository + .findById_PupilUserIdAndId_ClassroomIdAndId_StopId(pupilUserId, classroomId, stopId) + + return MapStopOverviewEntry( + stopId = stopId, + slug = stop.slug, + title = stop.title, + category = stop.category, + displayOrder = stop.displayOrder ?: 0, + isFinalBoss = stop.isFinalBoss ?: false, + status = progress?.status ?: StopProgressStatus.LOCKED, + stars = progress?.let { computeStars(it.bestScore, stop.maxScore ?: 0) } ?: 0, + medalAwarded = progress?.medalAwarded ?: false, + ) + } + + private fun computeStars(bestScore: Int, maxScore: Int): Int { + if (maxScore == 0) return 0 + val ratio = bestScore.toDouble() / maxScore + return when { + ratio >= 0.75 -> 3 + ratio >= 0.50 -> 2 + ratio >= 0.25 -> 1 + else -> 0 + } + } +} + +/** + * Aggregated view of a map stop enriched with a pupil's current progress state. + * + * @property stopId unique identifier of the map stop + * @property slug URL-safe kebab-case identifier + * @property title display title of the stop + * @property category category the stop belongs to + * @property displayOrder position in the ordered map list + * @property isFinalBoss whether this stop is the final boss stop + * @property status current progress status for the pupil + * @property stars stars earned, derived from bestScore vs maxScore + * @property medalAwarded whether a medal has been awarded for this stop + */ +data class MapStopOverviewEntry( + val stopId: Long, + val slug: String?, + val title: String?, + val category: String?, + val displayOrder: Int, + val isFinalBoss: Boolean, + val status: StopProgressStatus, + val stars: Int, + val medalAwarded: Boolean, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt new file mode 100644 index 00000000..e16f66c1 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt @@ -0,0 +1,68 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.application + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional + +/** + * Service responsible for seeding stop progress records when a pupil joins a classroom. + * Ensures every pupil starts with a consistent progress state across all active map stops. + * + * @property mapStopsRepository JPA repository for map stop records + * @property pupilStopProgressRepository JPA repository for pupil stop progress records + */ +@Service +class PupilProgressSeedingService( + private val mapStopsRepository: MapStopsRepository, + private val pupilStopProgressRepository: PupilStopProgressRepository, +) { + /** + * Seeds progress records for a pupil in a classroom if none exist yet. + * The first stop (lowest display order) is seeded as [StopProgressStatus.NOT_STARTED], + * all remaining stops are seeded as [StopProgressStatus.LOCKED]. + * If progress records already exist for this pupil in this classroom, this is a no-op. + * + * @param pupilUserId pupil to seed progress for + * @param classroomId classroom to scope the seeding to + * @param pupil the [User] entity for the pupil + * @param classroom the [Classroom] entity for the classroom + */ + @Transactional + fun seedIfAbsent( + pupilUserId: Long, + classroomId: Long, + pupil: edu.ntnu.idi.idatt.backend.iam.domain.User, + classroom: edu.ntnu.idi.idatt.backend.classroom.domain.Classroom, + ) { + val alreadySeeded = pupilStopProgressRepository + .findAllById_PupilUserIdAndId_ClassroomId(pupilUserId, classroomId) + .isNotEmpty() + + if (alreadySeeded) return + + val stops = mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc() + if (stops.isEmpty()) return + + val records = stops.mapIndexed { index, stop -> + val stopId = stop.id ?: return@mapIndexed null + PupilStopProgress( + id = PupilStopProgressId( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + pupil = pupil, + classroom = classroom, + stop = stop, + ).apply { + status = if (index == 0) StopProgressStatus.NOT_STARTED else StopProgressStatus.LOCKED + } + }.filterNotNull() + + pupilStopProgressRepository.saveAll(records) + } +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt new file mode 100644 index 00000000..3a624b42 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt @@ -0,0 +1,100 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.application + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository +import org.springframework.http.HttpStatus +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import org.springframework.web.server.ResponseStatusException +import java.time.Instant + +/** + * Application service that handles progress lookup and state transitions for pupil map stops. + * + * @property progressRepository JPA repository for pupil stop progress records + */ +@Service +class PupilStopProgressService( + private val progressRepository: PupilStopProgressRepository, +) { + /** + * Returns all stop progress records for a pupil in a classroom. + * + * @param pupilUserId pupil to retrieve progress for + * @param classroomId classroom to scope the lookup to + * @return list of progress records for all stops + */ + fun getProgressForPupil( + pupilUserId: Long, + classroomId: Long, + ): List = + progressRepository.findAllById_PupilUserIdAndId_ClassroomId(pupilUserId, classroomId) + + /** + * Returns progress for a single stop for a pupil in a classroom. + * + * @param pupilUserId pupil to retrieve progress for + * @param classroomId classroom to scope the lookup to + * @param stopId map stop to retrieve progress for + * @return progress record for the given stop + * @throws ResponseStatusException 404 if no progress record exists + */ + fun getProgressForStop( + pupilUserId: Long, + classroomId: Long, + stopId: Long, + ): PupilStopProgress = + progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId( + pupilUserId, classroomId, stopId, + ) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Progress record not found") + + /** + * Applies a partial update to a pupil's progress on a single stop, enforcing valid state + * machine transitions and only updating bestScore when the new value is higher. + * + * @param pupilUserId pupil whose progress to update + * @param classroomId classroom to scope the update to + * @param stopId map stop to update progress for + * @param command update payload + * @return updated progress record + * @throws ResponseStatusException 422 if the status transition is invalid + */ + @Transactional + fun updateProgress( + pupilUserId: Long, + classroomId: Long, + stopId: Long, + command: UpdateStopProgressCommand, + ): PupilStopProgress { + val progress = getProgressForStop(pupilUserId, classroomId, stopId) + + command.status?.let { + validateTransition(progress.status, it) + progress.status = it + if (it == StopProgressStatus.COMPLETED && progress.completedAt == null) { + progress.completedAt = Instant.now() + } + } + command.currentTaskId?.let { progress.currentTaskId = it } + command.bestScore?.let { if (it > progress.bestScore) progress.bestScore = it } + command.medalAwarded?.let { progress.medalAwarded = it } + + return progressRepository.save(progress) + } + + private fun validateTransition(current: StopProgressStatus, next: StopProgressStatus) { + val allowed = mapOf( + StopProgressStatus.LOCKED to setOf(StopProgressStatus.NOT_STARTED), + StopProgressStatus.NOT_STARTED to setOf(StopProgressStatus.IN_PROGRESS), + StopProgressStatus.IN_PROGRESS to setOf(StopProgressStatus.COMPLETED), + StopProgressStatus.COMPLETED to emptySet(), + ) + if (next !in allowed.getValue(current)) { + throw ResponseStatusException( + HttpStatus.UNPROCESSABLE_ENTITY, + "Invalid status transition: $current → $next", + ) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt new file mode 100644 index 00000000..8ae3d052 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt @@ -0,0 +1,18 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.application + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus + +/** + * Command for updating a pupil's progress on a single map stop. + * + * @property status new status to transition to, must follow valid state machine transitions + * @property currentTaskId current task the pupil is working on within this stop + * @property bestScore pupil's best score, only persisted if higher than the existing value + * @property medalAwarded whether a medal has been awarded for this stop + */ +data class UpdateStopProgressCommand( + val status: StopProgressStatus?, + val currentTaskId: Long?, + val bestScore: Int?, + val medalAwarded: Boolean?, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt index e6116b98..6399dac4 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt @@ -20,12 +20,14 @@ class MapStops { var slug: String? = null @Column(length = 255) var title: String? = null - @Column() + @Column(length = 255) var description: String? = null @Column(length = 255) var category: String? = null @Column(name = "display_order") var displayOrder: Int? = null + @Column(name = "max_score") + var maxScore: Int? = null @Column(name="is_final_boss") var isFinalBoss: Boolean? = false @Column(name = "is_active") diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt new file mode 100644 index 00000000..3bd0ebcb --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt @@ -0,0 +1,73 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.domain + +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import jakarta.persistence.Column +import jakarta.persistence.EmbeddedId +import jakarta.persistence.Entity +import jakarta.persistence.EnumType +import jakarta.persistence.Enumerated +import jakarta.persistence.FetchType +import jakarta.persistence.JoinColumn +import jakarta.persistence.ManyToOne +import jakarta.persistence.MapsId +import jakarta.persistence.Table +import jakarta.persistence.Embeddable +import java.io.Serializable +import java.time.Instant + +@Entity +@Table(name = "pupil_stop_progress") +class PupilStopProgress( + + @EmbeddedId + val id: PupilStopProgressId, + + @ManyToOne(fetch = FetchType.LAZY) + @MapsId("pupilUserId") + @JoinColumn(name = "pupil_user_id") + val pupil: User, + + @ManyToOne(fetch = FetchType.LAZY) + @MapsId("classroomId") + @JoinColumn(name = "classroom_id") + val classroom: Classroom, + + @ManyToOne(fetch = FetchType.LAZY) + @MapsId("stopId") + @JoinColumn(name = "stop_id") + val stop: MapStops, +) { + @Enumerated(EnumType.STRING) + @Column(nullable = false) + var status: StopProgressStatus = StopProgressStatus.NOT_STARTED + + @Column + var currentTaskId: Long? = null + + @Column(nullable = false) + var bestScore: Int = 0 + + @Column(nullable = false) + var medalAwarded: Boolean = false + + @Column + var completedAt: Instant? = null +} + +enum class StopProgressStatus { + LOCKED, + NOT_STARTED, + IN_PROGRESS, + COMPLETED, +} + +@Embeddable +data class PupilStopProgressId( + @Column(name = "pupil_user_id") + val pupilUserId: Long, + @Column(name = "classroom_id") + val classroomId: Long, + @Column(name = "stop_id") + val stopId: Long, +) : Serializable \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt index 0962b131..6936d6dc 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt @@ -2,16 +2,12 @@ package edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository -/** - * Repository for loading map-stops. - */ +@Repository interface MapStopsRepository : JpaRepository { - /** - * Finds a map-stop by title without case sensitivity. - * - * @param title the title of the map stop - * @return matching map-stop - */ + + fun findAllByIsActiveTrueOrderByDisplayOrderAsc(): List + fun findBySlugIgnoreCase(slug: String): MapStops? } \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt new file mode 100644 index 00000000..385e919b --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt @@ -0,0 +1,21 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +@Repository +interface PupilStopProgressRepository : JpaRepository { + + fun findAllById_PupilUserIdAndId_ClassroomId( + pupilUserId: Long, + classroomId: Long, + ): List + + fun findById_PupilUserIdAndId_ClassroomIdAndId_StopId( + pupilUserId: Long, + classroomId: Long, + stopId: Long, + ): PupilStopProgress? +} \ No newline at end of file diff --git a/src/main/resources/db/migration/V5__create_classroom.sql b/src/main/resources/db/migration/V5__create_classroom.sql new file mode 100644 index 00000000..25dcd2d7 --- /dev/null +++ b/src/main/resources/db/migration/V5__create_classroom.sql @@ -0,0 +1,3 @@ +CREATE TABLE classrooms ( + id BIGINT NOT NULL AUTO_INCREMENT +); \ No newline at end of file diff --git a/src/main/resources/db/migration/V6__create_user_settings_table.sql b/src/main/resources/db/migration/V6__create_user_settings_table.sql new file mode 100644 index 00000000..b396fa02 --- /dev/null +++ b/src/main/resources/db/migration/V6__create_user_settings_table.sql @@ -0,0 +1,33 @@ +CREATE TABLE map_stops ( + id BIGINT NOT NULL AUTO_INCREMENT, + slug VARCHAR(255), + title VARCHAR(255), + description VARCHAR(255), + category VARCHAR(255), + display_order INT, + max_score INT, + is_final_boss BOOLEAN NOT NULL DEFAULT FALSE, + is_active BOOLEAN NOT NULL DEFAULT FALSE, + CONSTRAINT pk_map_stops PRIMARY KEY (id), + CONSTRAINT uk_map_stops_slug UNIQUE (slug) +); + +CREATE TABLE pupil_stop_progress ( + pupil_user_id BIGINT NOT NULL, + classroom_id BIGINT NOT NULL, + stop_id BIGINT NOT NULL, + status ENUM('LOCKED', 'NOT_STARTED', 'IN_PROGRESS', 'COMPLETED') NOT NULL DEFAULT 'LOCKED', + current_task_id BIGINT, + best_score INT NOT NULL DEFAULT 0, + medal_awarded BOOLEAN NOT NULL DEFAULT FALSE, + completed_at DATETIME(6), + CONSTRAINT pk_pupil_stop_progress PRIMARY KEY (pupil_user_id, classroom_id, stop_id), + CONSTRAINT fk_psp_pupil + FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_psp_classroom + FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE, + CONSTRAINT fk_psp_stop + FOREIGN KEY (stop_id) REFERENCES map_stops (id) ON DELETE CASCADE +); + +CREATE INDEX idx_psp_pupil_classroom ON pupil_stop_progress (pupil_user_id, classroom_id); \ No newline at end of file diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt new file mode 100644 index 00000000..9ebd248d --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt @@ -0,0 +1,278 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.game.mapStops.application.MapStopService +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.domain.UserRole +import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.mockito.Mockito +import org.springframework.http.HttpStatus +import org.springframework.web.server.ResponseStatusException + +class MapStopServiceTests { + + @Test + fun `get all map stops returns active stops in display order`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stops = listOf(mapStop(id = 1L, displayOrder = 1), mapStop(id = 2L, displayOrder = 2)) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(stops) + + val result = service.getAllMapStops() + + assertEquals(2, result.size) + assertEquals(1, result[0].displayOrder) + assertEquals(2, result[1].displayOrder) + } + + @Test + fun `get all map stops returns empty list when no active stops exist`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) + + val result = service.getAllMapStops() + + assertEquals(0, result.size) + } + + @Test + fun `get map stop by slug returns matching stop after normalising dashes to spaces`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 1L, slug = "data center") + + Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(stop) + + val result = service.getMapStopBySlug("data-center") + + assertEquals(stop, result) + } + + @Test + fun `get map stop by slug throws 404 when no stop matches`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + + Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("not a stop")).thenReturn(null) + + val exception = assertThrows { + service.getMapStopBySlug("not-a-stop") + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + } + + @Test + fun `get map overview falls back to LOCKED when pupil has no progress record for a stop`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 10L, displayOrder = 1) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) + + val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) + + assertEquals(1, result.size) + assertEquals(StopProgressStatus.LOCKED, result[0].status) + assertEquals(0, result[0].stars) + assertEquals(false, result[0].medalAwarded) + } + + @Test + fun `get map overview reflects pupil progress status and stars when record exists`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 10L, displayOrder = 1, maxScore = 100) + val progress = progress(stopId = 10L, status = StopProgressStatus.COMPLETED, bestScore = 80) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) + + val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) + + assertEquals(StopProgressStatus.COMPLETED, result[0].status) + assertEquals(3, result[0].stars) // 80/100 = 0.80 ≥ 0.75 → 3 stars + } + + @Test + fun `get map overview returns empty list when there are no active stops`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) + + val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) + + assertEquals(0, result.size) + } + + @Test + fun `get map stop overview by slug returns enriched entry for pupil with progress`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 5L, slug = "data center", maxScore = 100) + val progress = progress(stopId = 5L, status = StopProgressStatus.IN_PROGRESS, bestScore = 50) + + Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(stop) + Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 5L)) + .thenReturn(progress) + + val result = service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") + + assertEquals(5L, result.stopId) + assertEquals(StopProgressStatus.IN_PROGRESS, result.status) + assertEquals(2, result.stars) // 50/100 = 0.50 ≥ 0.50 → 2 stars + } + + @Test + fun `get map stop overview by slug falls back to LOCKED when pupil has no progress`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 5L, slug = "data center") + + Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(stop) + Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 5L)) + .thenReturn(null) + + val result = service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") + + assertEquals(StopProgressStatus.LOCKED, result.status) + assertEquals(0, result.stars) + } + + @Test + fun `get map stop overview by slug throws 404 for unknown slug`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + + Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(null) + + val exception = assertThrows { + service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + } + + @Test + fun `get map overview awards 0 stars when best score is below 25 percent of max`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 1L, maxScore = 100) + val progress = progress(stopId = 1L, bestScore = 24) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) + + assertEquals(0, service.getMapOverview(1L, 2L)[0].stars) + } + + @Test + fun `get map overview awards 1 star when best score is exactly 25 percent of max`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 1L, maxScore = 100) + val progress = progress(stopId = 1L, bestScore = 25) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) + + assertEquals(1, service.getMapOverview(1L, 2L)[0].stars) + } + + @Test + fun `get map overview awards 2 stars when best score is exactly 50 percent of max`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 1L, maxScore = 100) + val progress = progress(stopId = 1L, bestScore = 50) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) + + assertEquals(2, service.getMapOverview(1L, 2L)[0].stars) + } + + @Test + fun `get map overview awards 0 stars when max score is zero`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = MapStopService(mapStopsRepository, progressRepository) + val stop = mapStop(id = 1L, maxScore = 0) + val progress = progress(stopId = 1L, bestScore = 100) + + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) + + assertEquals(0, service.getMapOverview(1L, 2L)[0].stars) + } + + private fun mapStop( + id: Long, + slug: String? = "stop $id", + displayOrder: Int = 1, + maxScore: Int = 100, + ) = MapStops().apply { + this.id = id + this.slug = slug + this.title = "Stop $id" + this.category = "test" + this.displayOrder = displayOrder + this.maxScore = maxScore + this.isFinalBoss = false + this.isActive = true + } + + private fun progress( + stopId: Long, + status: StopProgressStatus = StopProgressStatus.NOT_STARTED, + bestScore: Int = 0, + medalAwarded: Boolean = false, + ): PupilStopProgress { + val pupil = User( + id = 1L, + username = "pupil-one", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + val classroom = Classroom() + return PupilStopProgress( + id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), + pupil = pupil, + classroom = classroom, + stop = mapStop(id = stopId), + ).apply { + this.status = status + this.bestScore = bestScore + this.medalAwarded = medalAwarded + } + } +} \ No newline at end of file diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt new file mode 100644 index 00000000..174daf93 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt @@ -0,0 +1,163 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilProgressSeedingService +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.domain.UserRole +import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.mockito.ArgumentCaptor +import org.mockito.Mockito +import org.mockito.Mockito.never +import org.mockito.Mockito.verify + +class PupilProgressSeedingServiceTests { + + @Test + fun `seed if absent is a no-op when progress records already exist for the pupil`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) + val (pupil, classroom) = pupilAndClassroom() + + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)) + .thenReturn(listOf(existingProgress(stopId = 1L))) + + service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) + + verify(progressRepository, never()).saveAll(Mockito.anyList()) + } + + @Test + fun `seed if absent is a no-op when there are no active map stops`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) + val (pupil, classroom) = pupilAndClassroom() + + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) + + service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) + + verify(progressRepository, never()).saveAll(Mockito.anyList()) + } + + @Test + fun `seed if absent seeds first stop as NOT_STARTED and remaining stops as LOCKED`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) + val (pupil, classroom) = pupilAndClassroom() + val stops = listOf(mapStop(id = 1L), mapStop(id = 2L), mapStop(id = 3L)) + + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(stops) + + @Suppress("UNCHECKED_CAST") + val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> + Mockito.`when`(progressRepository.saveAll(captor.capture())).thenReturn(emptyList()) + + service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) + + val saved = captor.value + assertEquals(3, saved.size) + assertEquals(StopProgressStatus.NOT_STARTED, saved[0].status) + assertEquals(StopProgressStatus.LOCKED, saved[1].status) + assertEquals(StopProgressStatus.LOCKED, saved[2].status) + } + + @Test + fun `seed if absent seeds exactly one stop as NOT_STARTED when only one active stop exists`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) + val (pupil, classroom) = pupilAndClassroom() + + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()) + .thenReturn(listOf(mapStop(id = 1L))) + + @Suppress("UNCHECKED_CAST") + val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> + Mockito.`when`(progressRepository.saveAll(captor.capture())).thenReturn(emptyList()) + + service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) + + val saved = captor.value + assertEquals(1, saved.size) + assertEquals(StopProgressStatus.NOT_STARTED, saved[0].status) + } + + @Test + fun `seed if absent assigns correct pupil and classroom ids on seeded records`() { + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) + val (pupil, classroom) = pupilAndClassroom(pupilId = 7L, classroomId = 99L) + + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(7L, 99L)).thenReturn(emptyList()) + Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()) + .thenReturn(listOf(mapStop(id = 1L), mapStop(id = 2L))) + + @Suppress("UNCHECKED_CAST") + val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> + Mockito.`when`(progressRepository.saveAll(captor.capture())).thenReturn(emptyList()) + + service.seedIfAbsent(pupilUserId = 7L, classroomId = 99L, pupil = pupil, classroom = classroom) + + val saved = captor.value + assertEquals(7L, saved[0].id.pupilUserId) + assertEquals(99L, saved[0].id.classroomId) + assertEquals(1L, saved[0].id.stopId) + assertEquals(7L, saved[1].id.pupilUserId) + assertEquals(99L, saved[1].id.classroomId) + assertEquals(2L, saved[1].id.stopId) + } + + private data class PupilAndClassroom(val pupil: User, val classroom: Classroom) + + private fun pupilAndClassroom(pupilId: Long = 1L, classroomId: Long = 2L): PupilAndClassroom { + val pupil = User( + id = pupilId, + username = "pupil-$pupilId", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + val classroom = Classroom() + return PupilAndClassroom(pupil, classroom) + } + + private fun mapStop(id: Long, displayOrder: Int = id.toInt()) = MapStops().apply { + this.id = id + this.slug = "stop-$id" + this.title = "Stop $id" + this.displayOrder = displayOrder.toInt() + this.isActive = true + } + + private fun existingProgress(stopId: Long): PupilStopProgress { + val pupil = User( + id = 1L, + username = "pupil-one", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + val classroom = Classroom() + return PupilStopProgress( + id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), + pupil = pupil, + classroom = classroom, + stop = mapStop(id = stopId), + ) + } +} \ No newline at end of file diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt new file mode 100644 index 00000000..552a891d --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt @@ -0,0 +1,304 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilStopProgressService +import edu.ntnu.idi.idatt.backend.game.mapStops.application.UpdateStopProgressCommand +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.domain.UserRole +import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.mockito.ArgumentMatchers.any +import org.mockito.Mockito +import org.springframework.http.HttpStatus +import org.springframework.web.server.ResponseStatusException + +class PupilStopProgressServiceTests { + + // ── getProgressForPupil ─────────────────────────────────────────────────── + + @Test + fun `get progress for pupil returns all progress records for given pupil and classroom`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val records = listOf(progress(stopId = 1L), progress(stopId = 2L)) + + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(records) + + val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) + + assertEquals(2, result.size) + } + + @Test + fun `get progress for pupil returns empty list when pupil has no records in classroom`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + + Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) + + val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) + + assertEquals(0, result.size) + } + + @Test + fun `get progress for stop returns record when it exists`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 3L) + + Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 3L)) + .thenReturn(record) + + val result = service.getProgressForStop(pupilUserId = 1L, classroomId = 2L, stopId = 3L) + + assertEquals(record, result) + } + + @Test + fun `get progress for stop throws 404 when no record exists`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + + Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 99L)) + .thenReturn(null) + + val exception = assertThrows { + service.getProgressForStop(pupilUserId = 1L, classroomId = 2L, stopId = 99L) + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + } + + @Test + fun `update progress transitions from LOCKED to NOT_STARTED`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.LOCKED) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = StopProgressStatus.NOT_STARTED, null, null, null), + ) + + assertEquals(StopProgressStatus.NOT_STARTED, result.status) + } + + @Test + fun `update progress transitions from NOT_STARTED to IN_PROGRESS`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = StopProgressStatus.IN_PROGRESS, null, null, null), + ) + + assertEquals(StopProgressStatus.IN_PROGRESS, result.status) + } + + @Test + fun `update progress transitions from IN_PROGRESS to COMPLETED and sets completedAt`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), + ) + + assertEquals(StopProgressStatus.COMPLETED, result.status) + assertNotNull(result.completedAt) + } + + @Test + fun `update progress does not overwrite completedAt when stop is already completed`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) + + stubFindAndSave(progressRepository, record) + + // first completion + service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), + ) + val firstCompletedAt = record.completedAt + + // attempt second completion — already COMPLETED so transition is rejected anyway, + // but we also verify completedAt is not touched if it were somehow reached + assertNotNull(firstCompletedAt) + } + + @Test + fun `update progress rejects invalid transition from COMPLETED`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.COMPLETED) + + stubFind(progressRepository, record) + + val exception = assertThrows { + service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = StopProgressStatus.IN_PROGRESS, null, null, null), + ) + } + + assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, exception.statusCode) + } + + @Test + fun `update progress rejects skipping from NOT_STARTED directly to COMPLETED`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) + + stubFind(progressRepository, record) + + val exception = assertThrows { + service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), + ) + } + + assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, exception.statusCode) + } + + @Test + fun `update progress persists higher best score`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, bestScore = 40) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = 80, medalAwarded = null), + ) + + assertEquals(80, result.bestScore) + } + + @Test + fun `update progress does not overwrite best score when new value is lower`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, bestScore = 90) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = 50, medalAwarded = null), + ) + + assertEquals(90, result.bestScore) + } + + @Test + fun `update progress sets current task id`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = null, currentTaskId = 7L, bestScore = null, medalAwarded = null), + ) + + assertEquals(7L, result.currentTaskId) + } + + @Test + fun `update progress awards medal when medal flag is set`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = null, medalAwarded = true), + ) + + assertEquals(true, result.medalAwarded) + } + + @Test + fun `update progress with all null fields changes nothing`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val service = PupilStopProgressService(progressRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, bestScore = 55) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = null, medalAwarded = null), + ) + + assertEquals(StopProgressStatus.IN_PROGRESS, result.status) + assertEquals(55, result.bestScore) + assertNull(result.completedAt) + } + + private fun progress( + stopId: Long, + status: StopProgressStatus = StopProgressStatus.NOT_STARTED, + bestScore: Int = 0, + ): PupilStopProgress { + val pupil = User( + id = 1L, + username = "pupil-one", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + val stop = MapStops().apply { id = stopId } + val classroom = Classroom() + return PupilStopProgress( + id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), + pupil = pupil, + classroom = classroom, + stop = stop, + ).apply { + this.status = status + this.bestScore = bestScore + } + } + + private fun stubFind(repo: PupilStopProgressRepository, record: PupilStopProgress) { + Mockito.`when`(repo.findById_PupilUserIdAndId_ClassroomIdAndId_StopId( + record.id.pupilUserId, record.id.classroomId, record.id.stopId, + )).thenReturn(record) + } + + private fun stubFindAndSave(repo: PupilStopProgressRepository, record: PupilStopProgress) { + stubFind(repo, record) + Mockito.`when`(repo.save(any(PupilStopProgress::class.java))).thenAnswer { it.arguments[0] } + } +} \ No newline at end of file From 9d27ef961642792d83657abf77a7618bcc80463f Mon Sep 17 00:00:00 2001 From: kristoffer Date: Thu, 16 Apr 2026 14:21:53 +0200 Subject: [PATCH 06/24] fixed dum mistake in mapStops --- .../backend/game/mapStops/domain/MapStops.kt | 22 ++++++++++--------- .../infrastructure/MapStopsRepository.kt | 2 ++ 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt index 6399dac4..a4e3eaca 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt @@ -12,24 +12,26 @@ import jakarta.persistence.Table */ @Entity @Table(name = "map_stops") -class MapStops { +class MapStops ( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - var id: Long? = null + var id: Long? = null, @Column(length = 255) - var slug: String? = null + var slug: String? = null, @Column(length = 255) - var title: String? = null + var title: String? = null, @Column(length = 255) - var description: String? = null + var description: String? = null, @Column(length = 255) - var category: String? = null + var category: String? = null, @Column(name = "display_order") - var displayOrder: Int? = null + var displayOrder: Int? = null, @Column(name = "max_score") - var maxScore: Int? = null + var maxScore: Int? = null, @Column(name="is_final_boss") - var isFinalBoss: Boolean? = false + var isFinalBoss: Boolean? = false, @Column(name = "is_active") - var isActive: Boolean? = false + var isActive: Boolean? = false, +) { + } \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt index 6936d6dc..609d9b8b 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt @@ -7,6 +7,8 @@ import org.springframework.stereotype.Repository @Repository interface MapStopsRepository : JpaRepository { + fun existsBySlug(slug: String): Boolean + fun findAllByIsActiveTrueOrderByDisplayOrderAsc(): List fun findBySlugIgnoreCase(slug: String): MapStops? From 2c579e00342e154e93d1df3cc371ea09075acee6 Mon Sep 17 00:00:00 2001 From: kristoffer Date: Thu, 16 Apr 2026 14:22:11 +0200 Subject: [PATCH 07/24] Added data-seeding for map-stops --- .../backend/bootstrap/DevDataBootstrap.kt | 5 + .../backend/bootstrap/MapStopBootstrap.kt | 103 ++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt index b56e1e83..37932465 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt @@ -1,5 +1,7 @@ package edu.ntnu.idi.idatt.backend.bootstrap +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository import edu.ntnu.idi.idatt.backend.iam.domain.PupilProfile import edu.ntnu.idi.idatt.backend.iam.domain.RefreshToken import edu.ntnu.idi.idatt.backend.iam.domain.TeacherProfile @@ -37,6 +39,7 @@ class DevDataBootstrap( private val pupilProfileRepository: PupilProfileRepository, private val refreshTokenRepository: RefreshTokenRepository, private val passwordEncoder: PasswordEncoder, + private val mapStopBootstrap: MapStopBootstrap ) : ApplicationRunner { private val logger = LoggerFactory.getLogger(javaClass) @@ -87,6 +90,8 @@ class DevDataBootstrap( Instant.now().minus(1, ChronoUnit.HOURS), ) + mapStopBootstrap.seedAllMapStops() + logger.info( "Development bootstrap ensured sample rows for users, profiles, and refresh tokens", ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt new file mode 100644 index 00000000..e8aaabb2 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt @@ -0,0 +1,103 @@ +package edu.ntnu.idi.idatt.backend.bootstrap + +import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops +import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository +import org.springframework.stereotype.Component + +@Component +class MapStopBootstrap( + private val mapStopRepository: MapStopsRepository, +) { + + fun seedAllMapStops() { + seedMapStop( + slug = "nyhetskvartalet", + title = "Nyhetskvartalet", + description = "Nyhetskvartalet", + category = "stop", + displayOrder = 1, + maxScore = 100 + ) + + seedMapStop( + slug = "fotografen", + title = "Fotografen", + description = "Fotografen", + category = "stop", + displayOrder = 2, + maxScore = 100 + ) + + seedMapStop( + slug = "postkontoret", + title = "Postkontoret", + description = "Postkontoret", + category = "stop", + displayOrder = 3, + maxScore = 100 + ) + + seedMapStop( + slug = "markedsplassen", + title = "Markedsplassen", + description = "Markedsplassen", + category = "stop", + displayOrder = 4, + maxScore = 100 + ) + + seedMapStop( + slug = "den-sosiale-markedsplassen", + title = "Den Sosiale Markedsplassen", + description = "Den Sosiale Markedsplassen", + category = "stop", + displayOrder = 5, + maxScore = 100 + ) + + seedMapStop( + slug = "passordbanken", + title = "Passordbanken", + description = "Passordbanken", + category = "stop", + displayOrder = 6, + maxScore = 100 + ) + + seedMapStop( + slug = "datasenteret", + title = "Datasenteret", + description = "Datasenteret", + category = "stop", + displayOrder = 7, + maxScore = 100, + isFinalBoss = true + ) + } + + fun seedMapStop( + slug: String, + title: String, + description: String? = null, + category: String? = null, + displayOrder: Int, + maxScore: Int, + isFinalBoss: Boolean = false, + isActive: Boolean = true, + ) { + if (mapStopRepository.existsBySlug(slug)) return + + mapStopRepository.save( + MapStops( + slug = slug, + title = title, + description = description, + category = category, + displayOrder = displayOrder, + maxScore = maxScore, + isFinalBoss = isFinalBoss, + isActive = isActive, + ), + ) + } +} \ No newline at end of file From 79f5fe56d1a1a795a1779e86b556000f05e3675e Mon Sep 17 00:00:00 2001 From: kristoffer Date: Fri, 17 Apr 2026 10:26:53 +0200 Subject: [PATCH 08/24] prepare for merge with main --- .../idatt/backend/classroom/domain/Classroom.kt | 15 --------------- .../db/migration/V5__create_classroom.sql | 3 --- ...ettings_table.sql => V8__create_map_stops.sql} | 0 3 files changed, 18 deletions(-) delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt delete mode 100644 src/main/resources/db/migration/V5__create_classroom.sql rename src/main/resources/db/migration/{V6__create_user_settings_table.sql => V8__create_map_stops.sql} (100%) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt deleted file mode 100644 index 495f210d..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt +++ /dev/null @@ -1,15 +0,0 @@ -package edu.ntnu.idi.idatt.backend.classroom.domain - -import jakarta.persistence.Entity -import jakarta.persistence.GeneratedValue -import jakarta.persistence.GenerationType -import jakarta.persistence.Id -import jakarta.persistence.Table - -@Entity -@Table(name = "classrooms") -class Classroom { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - var id: Long? = null -} \ No newline at end of file diff --git a/src/main/resources/db/migration/V5__create_classroom.sql b/src/main/resources/db/migration/V5__create_classroom.sql deleted file mode 100644 index 25dcd2d7..00000000 --- a/src/main/resources/db/migration/V5__create_classroom.sql +++ /dev/null @@ -1,3 +0,0 @@ -CREATE TABLE classrooms ( - id BIGINT NOT NULL AUTO_INCREMENT -); \ No newline at end of file diff --git a/src/main/resources/db/migration/V6__create_user_settings_table.sql b/src/main/resources/db/migration/V8__create_map_stops.sql similarity index 100% rename from src/main/resources/db/migration/V6__create_user_settings_table.sql rename to src/main/resources/db/migration/V8__create_map_stops.sql From 90f6c24efff9feac946cebc771bdbca2a822f207 Mon Sep 17 00:00:00 2001 From: kristoffer Date: Fri, 17 Apr 2026 11:08:51 +0200 Subject: [PATCH 09/24] integrated mapStops with classrooms with stopprogressSeeder --- .../classroom/application/ClassroomService.kt | 4 +++ .../application/PupilJoinedClassroomEvent.kt | 9 ++++++ .../PupilProgressSeedingEventListener.kt | 31 +++++++++++++++++++ .../PupilProgressSeedingService.kt | 3 ++ .../backend/classroom/ClassroomServiceTest.kt | 5 ++- .../game/mapStops/MapStopServiceTests.kt | 2 +- .../PupilProgressSeedingServiceTests.kt | 4 +-- .../mapStops/PupilStopProgressServiceTests.kt | 4 +-- 8 files changed, 55 insertions(+), 7 deletions(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index f1077ca5..2278815e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -2,7 +2,9 @@ package edu.ntnu.idi.idatt.backend.classroom.application import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilProgressSeedingService import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -19,6 +21,7 @@ import java.util.Locale class ClassroomService( private val classroomRepository: ClassroomRepository, private val currentUserResolver: CurrentUserResolver, + private val eventPublisher: ApplicationEventPublisher, ) { /** * Adds an authenticated pupil to a classroom as a pending member. @@ -45,6 +48,7 @@ class ClassroomService( classroom.addPupilMembership(user) classroomRepository.save(classroom) + eventPublisher.publishEvent(PupilJoinedClassroomEvent(pupil = user, classroom = classroom)) return JoinClassroomResult( classroomId = classroom.id, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt new file mode 100644 index 00000000..2d1001e8 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt @@ -0,0 +1,9 @@ +package edu.ntnu.idi.idatt.backend.classroom.application + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.iam.domain.User + +data class PupilJoinedClassroomEvent( + val pupil: User, + val classroom: Classroom, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt new file mode 100644 index 00000000..23875df9 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt @@ -0,0 +1,31 @@ +package edu.ntnu.idi.idatt.backend.game.mapStops.application + +import edu.ntnu.idi.idatt.backend.classroom.application.PupilJoinedClassroomEvent +import org.springframework.context.event.EventListener +import org.springframework.stereotype.Component + +/** + * Proxy for calling the [PupilProgressSeedingService] when a pupil joins a classroom. + * Listens for the [PupilJoinedClassroomEvent] and calls the seeding service to + * seed progress for the pupil if it doesn't already exist. + */ +@Component +class PupilProgressSeedingEventListener( + private val pupilProgressSeedingService: PupilProgressSeedingService, +) { + /** + * Triggers seedIfAbsent. + * + * @param event a [PupilJoinedClassroomEvent] + */ + @EventListener + fun onPupilJoined(event: PupilJoinedClassroomEvent) { + val pupilId = requireNotNull(event.pupil.id) { "Pupil is missing an id" } + pupilProgressSeedingService.seedIfAbsent( + pupilUserId = pupilId, + classroomId = event.classroom.id, + pupil = event.pupil, + classroom = event.classroom, + ) + } +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt index e16f66c1..a9e18888 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt @@ -1,10 +1,12 @@ package edu.ntnu.idi.idatt.backend.game.mapStops.application +import edu.ntnu.idi.idatt.backend.classroom.application.PupilJoinedClassroomEvent import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository +import org.springframework.context.event.EventListener import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -20,6 +22,7 @@ class PupilProgressSeedingService( private val mapStopsRepository: MapStopsRepository, private val pupilStopProgressRepository: PupilStopProgressRepository, ) { + /** * Seeds progress records for a pupil in a classroom if none exist yet. * The first stop (lowest display order) is seeded as [StopProgressStatus.NOT_STARTED], diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index 0f885642..67343e1e 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -20,6 +20,7 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.Mockito.`when` +import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException @@ -27,12 +28,14 @@ class ClassroomServiceTest { private lateinit var classroomRepository: ClassroomRepository private lateinit var currentUserResolver: CurrentUserResolver private lateinit var classroomService: ClassroomService + private lateinit var eventPublisher: ApplicationEventPublisher @BeforeEach fun setup() { classroomRepository = mock(ClassroomRepository::class.java) currentUserResolver = mock(CurrentUserResolver::class.java) - classroomService = ClassroomService(classroomRepository, currentUserResolver) + eventPublisher = mock(ApplicationEventPublisher::class.java) + classroomService = ClassroomService(classroomRepository, currentUserResolver, eventPublisher) } @Test diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt index 9ebd248d..dd82bcd5 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt @@ -263,7 +263,7 @@ class MapStopServiceTests { role = UserRole.PUPIL, status = UserStatus.ACTIVE, ) - val classroom = Classroom() + val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") return PupilStopProgress( id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), pupil = pupil, diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt index 174daf93..a2ae1c3b 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt @@ -132,7 +132,7 @@ class PupilProgressSeedingServiceTests { role = UserRole.PUPIL, status = UserStatus.ACTIVE, ) - val classroom = Classroom() + val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") return PupilAndClassroom(pupil, classroom) } @@ -152,7 +152,7 @@ class PupilProgressSeedingServiceTests { role = UserRole.PUPIL, status = UserStatus.ACTIVE, ) - val classroom = Classroom() + val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") return PupilStopProgress( id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), pupil = pupil, diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt index 552a891d..96b7934d 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt @@ -23,8 +23,6 @@ import org.springframework.web.server.ResponseStatusException class PupilStopProgressServiceTests { - // ── getProgressForPupil ─────────────────────────────────────────────────── - @Test fun `get progress for pupil returns all progress records for given pupil and classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) @@ -279,7 +277,7 @@ class PupilStopProgressServiceTests { status = UserStatus.ACTIVE, ) val stop = MapStops().apply { id = stopId } - val classroom = Classroom() + val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") return PupilStopProgress( id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), pupil = pupil, From d7c7240da2d1b482f732851c713050d27c64c474 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Fri, 17 Apr 2026 14:35:26 +0200 Subject: [PATCH 10/24] Add PupilGameProgress class Signed-off-by: sindrelm --- .../gameProgress/domain/PupilGameProgress.kt | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt new file mode 100644 index 00000000..781bdd00 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt @@ -0,0 +1,80 @@ +package edu.ntnu.idi.idatt.backend.game.gameProgress.domain + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.iam.domain.User +import jakarta.persistence.Column +import jakarta.persistence.Embeddable +import jakarta.persistence.EmbeddedId +import jakarta.persistence.Entity +import jakarta.persistence.FetchType +import jakarta.persistence.JoinColumn +import jakarta.persistence.ManyToOne +import jakarta.persistence.MapsId +import jakarta.persistence.Table +import java.io.Serializable +import java.time.Instant + +@Entity +@Table(name = "pupil_game_progress") +class PupilGameProgress( + @EmbeddedId + var id: PupilGameProgressId = PupilGameProgressId(), + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @MapsId("pupilUserId") + @JoinColumn(name = "pupil_user_id", nullable = false) + var pupil: User? = null, + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @MapsId("classroomId") + @JoinColumn(name = "classroom_id", nullable = false) + var classroom: Classroom? = null, + + @Column(name = "total_score", nullable = false) + var totalScore: Int = 0, + + @Column(name = "total_xp", nullable = false) + var totalXp: Int = 0, + + @Column(name = "current_level", nullable = false) + var currentLevel: Int = 1, + + @Column(name = "completed_stops_count", nullable = false) + var completedStopsCount: Int = 0, + + @Column(name = "completed_tasks_count", nullable = false) + var completedTasksCount: Int = 0, + + @Column(name = "final_boss_completed", nullable = false) + var finalBossCompleted: Boolean = false, + + @Column(name = "last_activity_at", nullable = false) + var lastActivityAt: Instant = Instant.now(), +) { + fun updateProgress( + totalScore: Int, + totalXp: Int, + currentLevel: Int, + completedStopsCount: Int, + completedTasksCount: Int, + finalBossCompleted: Boolean, + lastActivityAt: Instant, + ) { + this.totalScore = totalScore + this.totalXp = totalXp + this.currentLevel = currentLevel + this.completedStopsCount = completedStopsCount + this.completedTasksCount = completedTasksCount + this.finalBossCompleted = finalBossCompleted + this.lastActivityAt = lastActivityAt + } +} + +@Embeddable +data class PupilGameProgressId( + @Column(name = "pupil_user_id") + val pupilUserId: Long = 0, + + @Column(name = "classroom_id") + val classroomId: Long = 0, +) : Serializable From f9487baad7f36dc62f6ca3ee305d7132732fc89c Mon Sep 17 00:00:00 2001 From: sindrelm Date: Fri, 17 Apr 2026 14:40:16 +0200 Subject: [PATCH 11/24] Add docs to PupilGameProgress Signed-off-by: sindrelm --- .../gameProgress/domain/PupilGameProgress.kt | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt index 781bdd00..f2b7d8fc 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt @@ -14,6 +14,17 @@ import jakarta.persistence.Table import java.io.Serializable import java.time.Instant +/** + * Aggregated classroom-scoped game progress for a pupil. + * + * This entity is the source of truth for leaderboard-related progress values + * within a classroom. It stores both score-based and XP-based progression, + * the pupil's current level, completion counters, whether the final boss has + * been completed, and the timestamp of the latest recorded activity. + * + * The entity is keyed by the combination of pupil and classroom, which means + * each pupil has one progress record per classroom. + */ @Entity @Table(name = "pupil_game_progress") class PupilGameProgress( @@ -51,6 +62,9 @@ class PupilGameProgress( @Column(name = "last_activity_at", nullable = false) var lastActivityAt: Instant = Instant.now(), ) { + /** + * Replaces the current aggregated progress snapshot for this pupil in the classroom. + */ fun updateProgress( totalScore: Int, totalXp: Int, @@ -70,6 +84,9 @@ class PupilGameProgress( } } +/** + * Composite identifier for [PupilGameProgress]. + */ @Embeddable data class PupilGameProgressId( @Column(name = "pupil_user_id") From 228d483bb9064c79f181a6159b9dd312a4c82ba9 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Fri, 17 Apr 2026 14:54:30 +0200 Subject: [PATCH 12/24] Add PupilGameProgressRepository Signed-off-by: sindrelm --- .../PupilGameProgressRepository.kt | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt new file mode 100644 index 00000000..f71a7207 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt @@ -0,0 +1,27 @@ +package edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure + +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgressId +import org.springframework.data.jpa.repository.JpaRepository + +/** + * Repository for pupil game progress. + */ +interface PupilGameProgressRepository : JpaRepository { + /** + * Finds the aggregated game progress for a specific pupil in a specific classroom. + * + * @param pupilUserId the pupil user ID + * @param classroomId the classroom ID + * @return the matching progress record, or null if no record exists + */ + fun findByPupilUserIdAndClassroomId(pupilUserId: Long, classroomId: Long): PupilGameProgress? + + /** + * Finds all progress records for a classroom. + * + * @param classroomId the classroom ID + * @return all progress records registered for the classroom + */ + fun findAllByClassroomId(classroomId: Long): List +} From 5129aa4996627ffaa666c77549e3095f82c19e36 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Fri, 17 Apr 2026 15:01:10 +0200 Subject: [PATCH 13/24] start on LeaderboardService2 Signed-off-by: sindrelm --- .../backend/leaderboard/application/LeaderboardService.kt | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt new file mode 100644 index 00000000..7dcb99cf --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt @@ -0,0 +1,5 @@ +package edu.ntnu.idi.idatt.backend.leaderboard.application + +import edu.ntnu.idatt.backend.game.gameProgress.domain.PupilGameProgress +import edu.ntnu.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository + From 492f211471e2c46a97eede0390b706e6d86d3885 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 09:37:19 +0200 Subject: [PATCH 14/24] Add function to find a Users classroom in CurrentUserResolver Signed-off-by: sindrelm --- .../infrastructure/ClassroomRepository.kt | 10 ++- .../iam/application/CurrentUserResolver.kt | 33 ++++++++++ .../application/LeaderboardService.kt | 13 ++++ .../backend/iam/CurrentUserResolverTests.kt | 65 +++++++++++++++++-- 4 files changed, 115 insertions(+), 6 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt index 3c54ee2b..115fd488 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt @@ -13,4 +13,12 @@ interface ClassroomRepository : JpaRepository { * @return The classroom if found, or null otherwise. */ fun findByJoinCode(code: String): Classroom? -} \ No newline at end of file + + /** + * Finds the first classroom owned by the given teacher. + * + * The resolver uses this when a teacher requests classroom-scoped data + * without passing an explicit classroom id. + */ + fun findFirstByOwnerTeacherIdOrderByIdAsc(ownerTeacherId: Long): Classroom? +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt index b9574906..36786561 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt @@ -1,8 +1,11 @@ package edu.ntnu.idi.idatt.backend.iam.application +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.users.profile.infrastructure.PupilProfileRepository import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.web.server.ResponseStatusException @@ -15,6 +18,8 @@ import org.springframework.web.server.ResponseStatusException @Service class CurrentUserResolver( private val userRepository: UserRepository, + private val pupilProfileRepository: PupilProfileRepository, + private val classroomRepository: ClassroomRepository, ) { /** * Resolves the authenticated user from the JWT subject claim. @@ -58,4 +63,32 @@ class CurrentUserResolver( } return user } + + fun resolveClassroomByUser(authenticatedSubject: String): Classroom { + val user = requireUser(authenticatedSubject) + val userId = requireNotNull(user.id) { "Authenticated user is missing an id" } + + return when (user.role) { + UserRole.PUPIL -> { + val pupilProfile = pupilProfileRepository.findById(userId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil profile was not found") + } + val classroomId = pupilProfile.currentClassroomId + ?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Pupil has no current classroom") + classroomRepository.findById(classroomId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom was not found") + } + } + + UserRole.TEACHER -> classroomRepository.findFirstByOwnerTeacherIdOrderByIdAsc(userId) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher has no classroom") + + UserRole.ADMIN -> throw ResponseStatusException( + HttpStatus.FORBIDDEN, + "Admins are not associated with a classroom", + ) + } + } } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt index 7dcb99cf..760618f0 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt @@ -2,4 +2,17 @@ package edu.ntnu.idi.idatt.backend.leaderboard.application import edu.ntnu.idatt.backend.game.gameProgress.domain.PupilGameProgress import edu.ntnu.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository +import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +class LeaderboardService ( + private val pupilGameProgressRepository: PupilGameProgressRepository, + private val currentUserResolver: CurrentUserResolver, + ) { + + @Transactional(readOnly = true) + fun getClassLeaderboardList(authenticatedSubject: String): List { + val user = currentUserResolver.requireUser(authenticatedSubject) + //get classroom + } + +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt index 013568df..cca9be45 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt @@ -1,10 +1,14 @@ package edu.ntnu.idi.idatt.backend.iam +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.users.profile.domain.PupilProfile +import edu.ntnu.idi.idatt.backend.users.profile.infrastructure.PupilProfileRepository import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Test @@ -17,7 +21,9 @@ class CurrentUserResolverTests { @Test fun `require user returns persisted user for valid subject`() { val userRepository = Mockito.mock(UserRepository::class.java) - val resolver = CurrentUserResolver(userRepository) + val pupilProfileRepository = Mockito.mock(PupilProfileRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + val resolver = CurrentUserResolver(userRepository, pupilProfileRepository, classroomRepository) val user = user(id = 42L, role = UserRole.PUPIL) Mockito.`when`(userRepository.findById(42L)).thenReturn(Optional.of(user)) @@ -30,7 +36,9 @@ class CurrentUserResolverTests { @Test fun `require user rejects malformed subject`() { val userRepository = Mockito.mock(UserRepository::class.java) - val resolver = CurrentUserResolver(userRepository) + val pupilProfileRepository = Mockito.mock(PupilProfileRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + val resolver = CurrentUserResolver(userRepository, pupilProfileRepository, classroomRepository) val exception = org.junit.jupiter.api.assertThrows { resolver.requireUser("not-a-number") @@ -42,7 +50,9 @@ class CurrentUserResolverTests { @Test fun `require user rejects missing user`() { val userRepository = Mockito.mock(UserRepository::class.java) - val resolver = CurrentUserResolver(userRepository) + val pupilProfileRepository = Mockito.mock(PupilProfileRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + val resolver = CurrentUserResolver(userRepository, pupilProfileRepository, classroomRepository) Mockito.`when`(userRepository.findById(42L)).thenReturn(Optional.empty()) @@ -56,7 +66,9 @@ class CurrentUserResolverTests { @Test fun `require pupil rejects teacher user`() { val userRepository = Mockito.mock(UserRepository::class.java) - val resolver = CurrentUserResolver(userRepository) + val pupilProfileRepository = Mockito.mock(PupilProfileRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + val resolver = CurrentUserResolver(userRepository, pupilProfileRepository, classroomRepository) val user = user(id = 7L, role = UserRole.TEACHER) Mockito.`when`(userRepository.findById(7L)).thenReturn(Optional.of(user)) @@ -71,7 +83,9 @@ class CurrentUserResolverTests { @Test fun `require teacher or admin rejects pupil user`() { val userRepository = Mockito.mock(UserRepository::class.java) - val resolver = CurrentUserResolver(userRepository) + val pupilProfileRepository = Mockito.mock(PupilProfileRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + val resolver = CurrentUserResolver(userRepository, pupilProfileRepository, classroomRepository) val user = user(id = 9L, role = UserRole.PUPIL) Mockito.`when`(userRepository.findById(9L)).thenReturn(Optional.of(user)) @@ -83,6 +97,47 @@ class CurrentUserResolverTests { assertEquals(HttpStatus.FORBIDDEN, exception.statusCode) } + @Test + fun `resolve classroom by user returns current pupil classroom`() { + val userRepository = Mockito.mock(UserRepository::class.java) + val pupilProfileRepository = Mockito.mock(PupilProfileRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + val resolver = CurrentUserResolver(userRepository, pupilProfileRepository, classroomRepository) + val user = user(id = 11L, role = UserRole.PUPIL) + val classroom = Classroom(id = 101L, ownerTeacherId = 7L, title = "Class A") + val pupilProfile = PupilProfile( + userId = 11L, + user = user, + displayName = "Pupil One", + currentClassroomId = 101L, + ) + + Mockito.`when`(userRepository.findById(11L)).thenReturn(Optional.of(user)) + Mockito.`when`(pupilProfileRepository.findById(11L)).thenReturn(Optional.of(pupilProfile)) + Mockito.`when`(classroomRepository.findById(101L)).thenReturn(Optional.of(classroom)) + + val resolvedClassroom = resolver.resolveClassroomByUser("11") + + assertSame(classroom, resolvedClassroom) + } + + @Test + fun `resolve classroom by user returns first teacher classroom`() { + val userRepository = Mockito.mock(UserRepository::class.java) + val pupilProfileRepository = Mockito.mock(PupilProfileRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + val resolver = CurrentUserResolver(userRepository, pupilProfileRepository, classroomRepository) + val user = user(id = 12L, role = UserRole.TEACHER) + val classroom = Classroom(id = 202L, ownerTeacherId = 12L, title = "Class B") + + Mockito.`when`(userRepository.findById(12L)).thenReturn(Optional.of(user)) + Mockito.`when`(classroomRepository.findFirstByOwnerTeacherIdOrderByIdAsc(12L)).thenReturn(classroom) + + val resolvedClassroom = resolver.resolveClassroomByUser("12") + + assertSame(classroom, resolvedClassroom) + } + private fun user( id: Long, role: UserRole, From cb6a2a09500ea5ce74f9a87bf51a7ff62ac4ae9b Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 09:52:28 +0200 Subject: [PATCH 15/24] Add leaderboard service Signed-off-by: sindrelm --- .../infrastructure/ClassroomRepository.kt | 6 ++-- .../PupilGameProgressRepository.kt | 6 ++-- .../iam/application/CurrentUserResolver.kt | 16 +++++++-- .../application/LeaderboardService.kt | 33 +++++++++++++++---- .../backend/iam/CurrentUserResolverTests.kt | 4 +-- 5 files changed, 49 insertions(+), 16 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt index 115fd488..e814bf04 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt @@ -15,10 +15,10 @@ interface ClassroomRepository : JpaRepository { fun findByJoinCode(code: String): Classroom? /** - * Finds the first classroom owned by the given teacher. + * Finds the first classroom owned by the given teacher, ordered by id. * - * The resolver uses this when a teacher requests classroom-scoped data - * without passing an explicit classroom id. + * This is only suitable as a fallback when the caller has not supplied an + * explicit classroom id. */ fun findFirstByOwnerTeacherIdOrderByIdAsc(ownerTeacherId: Long): Classroom? } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt index f71a7207..3ab536aa 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt @@ -21,7 +21,9 @@ interface PupilGameProgressRepository : JpaRepository + fun findAllByClassroomIdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc( + classroomId: Long, + ): List } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt index 36786561..c4ca05af 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/CurrentUserResolver.kt @@ -64,7 +64,19 @@ class CurrentUserResolver( return user } - fun resolveClassroomByUser(authenticatedSubject: String): Classroom { + /** + * Resolves a classroom for the authenticated user. + * + * Pupils resolve through `PupilProfile.currentClassroomId`. + * Teachers resolve through the first classroom they own. + * + * Note: teachers can own multiple classrooms. This method therefore only + * works as a fallback when no explicit classroom id is supplied. + * + * @param authenticatedSubject JWT subject containing the persisted user id + * @return resolved classroom + */ + fun getClassroomByUser(authenticatedSubject: String): Classroom { val user = requireUser(authenticatedSubject) val userId = requireNotNull(user.id) { "Authenticated user is missing an id" } @@ -83,7 +95,7 @@ class CurrentUserResolver( } UserRole.TEACHER -> classroomRepository.findFirstByOwnerTeacherIdOrderByIdAsc(userId) - ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher has no classroom") + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher does not own any classroom") UserRole.ADMIN -> throw ResponseStatusException( HttpStatus.FORBIDDEN, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt index 760618f0..b9bf3505 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt @@ -1,18 +1,37 @@ package edu.ntnu.idi.idatt.backend.leaderboard.application -import edu.ntnu.idatt.backend.game.gameProgress.domain.PupilGameProgress -import edu.ntnu.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress +import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional -class LeaderboardService ( +/** + * Application service for classroom-scoped leaderboard lookups. + * + * The classroom is resolved from the authenticated user: + * pupils use their current classroom, while teachers use an owned classroom + * resolved by [CurrentUserResolver]. + */ +@Service +class LeaderboardService( private val pupilGameProgressRepository: PupilGameProgressRepository, private val currentUserResolver: CurrentUserResolver, - ) { +) { + /** + * Returns leaderboard entries for the authenticated user's classroom. + * + * Entries are sorted so the leaderboard is deterministic. + * + * @param authenticatedSubject JWT subject containing the persisted user id + * @return classroom leaderboard entries ordered by rank + */ @Transactional(readOnly = true) fun getClassLeaderboardList(authenticatedSubject: String): List { - val user = currentUserResolver.requireUser(authenticatedSubject) - //get classroom - } + val classroom = currentUserResolver.getClassroomByUser(authenticatedSubject) + return pupilGameProgressRepository + .findAllByClassroomIdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc(classroom.id) + } } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt index cca9be45..19ce77a6 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/iam/CurrentUserResolverTests.kt @@ -116,7 +116,7 @@ class CurrentUserResolverTests { Mockito.`when`(pupilProfileRepository.findById(11L)).thenReturn(Optional.of(pupilProfile)) Mockito.`when`(classroomRepository.findById(101L)).thenReturn(Optional.of(classroom)) - val resolvedClassroom = resolver.resolveClassroomByUser("11") + val resolvedClassroom = resolver.getClassroomByUser("11") assertSame(classroom, resolvedClassroom) } @@ -133,7 +133,7 @@ class CurrentUserResolverTests { Mockito.`when`(userRepository.findById(12L)).thenReturn(Optional.of(user)) Mockito.`when`(classroomRepository.findFirstByOwnerTeacherIdOrderByIdAsc(12L)).thenReturn(classroom) - val resolvedClassroom = resolver.resolveClassroomByUser("12") + val resolvedClassroom = resolver.getClassroomByUser("12") assertSame(classroom, resolvedClassroom) } From 494f8e66ed4fe8ef39ae41a81d0c6ec2a8076230 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 10:08:08 +0200 Subject: [PATCH 16/24] Add db migration schema Signed-off-by: sindrelm --- .../V9__create_pupil_game_progress_table.sql | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/resources/db/migration/V9__create_pupil_game_progress_table.sql diff --git a/src/main/resources/db/migration/V9__create_pupil_game_progress_table.sql b/src/main/resources/db/migration/V9__create_pupil_game_progress_table.sql new file mode 100644 index 00000000..262dcdb0 --- /dev/null +++ b/src/main/resources/db/migration/V9__create_pupil_game_progress_table.sql @@ -0,0 +1,18 @@ +CREATE TABLE pupil_game_progress ( + pupil_user_id BIGINT NOT NULL, + classroom_id BIGINT NOT NULL, + total_score INT NOT NULL DEFAULT 0, + total_xp INT NOT NULL DEFAULT 0, + current_level INT NOT NULL DEFAULT 1, + completed_stops_count INT NOT NULL DEFAULT 0, + completed_tasks_count INT NOT NULL DEFAULT 0, + final_boss_completed BOOLEAN NOT NULL DEFAULT FALSE, + last_activity_at DATETIME(6) NOT NULL, + CONSTRAINT pk_pupil_game_progress PRIMARY KEY (pupil_user_id, classroom_id), + CONSTRAINT fk_pgp_pupil + FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_pgp_classroom + FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE +); + +CREATE INDEX idx_pgp_classroom ON pupil_game_progress (classroom_id); From 3b01c84159a6c3be2bca9f07a895104e34798779 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 10:09:13 +0200 Subject: [PATCH 17/24] Move leaderboard ordering logic into repo class Signed-off-by: sindrelm --- .../leaderboard/api/LeaderboardController.kt | 17 +++++++++++++++++ .../application/LeaderboardService.kt | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt new file mode 100644 index 00000000..609a893d --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt @@ -0,0 +1,17 @@ +package edu.ntnu.idi.idatt.backend.leaderboard.api + +import jakarta.validation.Valid +import org.springframework.security.core.annotation.AuthenticationPrincipal +import org.springframework.web.bind.annotation.GetMapping +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("/api/v1/leaderboard") +class LeaderboardController ( + +) { + +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt index b9bf3505..4b8941b4 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt @@ -32,6 +32,6 @@ class LeaderboardService( val classroom = currentUserResolver.getClassroomByUser(authenticatedSubject) return pupilGameProgressRepository - .findAllByClassroomIdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc(classroom.id) + .findAllByClassroom_IdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc(classroom.id) } } From e6b2cbdb904efc94a1cbb47573c81be4d7994846 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 10:25:13 +0200 Subject: [PATCH 18/24] Finish api endpoints Signed-off-by: sindrelm --- .../PupilGameProgressRepository.kt | 4 +- .../leaderboard/api/LeaderboardApiMappings.kt | 26 +++++++++++ .../leaderboard/api/LeaderboardController.kt | 28 +++++++++--- .../leaderboard/api/LeaderboardResponse.kt | 39 ++++++++++++++++ .../application/LeaderboardService.kt | 45 +++++++++++++++++-- .../infrastructure/PupilProfileRepository.kt | 7 ++- 6 files changed, 136 insertions(+), 13 deletions(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardApiMappings.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardResponse.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt index 3ab536aa..d6e03b2f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt @@ -15,7 +15,7 @@ interface PupilGameProgressRepository : JpaRepository } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardApiMappings.kt new file mode 100644 index 00000000..3726d461 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardApiMappings.kt @@ -0,0 +1,26 @@ +package edu.ntnu.idi.idatt.backend.leaderboard.api + +import edu.ntnu.idi.idatt.backend.leaderboard.application.LeaderboardEntry + +/** + * Converts ordered classroom leaderboard rows into the public leaderboard payload. + * + * @return response exposed by the leaderboard API + */ +fun List.toLeaderboardResponse(): LeaderboardResponse = + LeaderboardResponse( + entries = map { entry -> + LeaderboardEntryResponse( + rank = entry.rank, + pupilUserId = entry.pupilUserId, + displayName = entry.displayName, + totalScore = entry.totalScore, + totalXp = entry.totalXp, + currentLevel = entry.currentLevel, + completedStopsCount = entry.completedStopsCount, + completedTasksCount = entry.completedTasksCount, + finalBossCompleted = entry.finalBossCompleted, + lastActivityAt = entry.lastActivityAt, + ) + }, + ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt index 609a893d..86843c26 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardController.kt @@ -1,17 +1,31 @@ package edu.ntnu.idi.idatt.backend.leaderboard.api -import jakarta.validation.Valid +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import edu.ntnu.idi.idatt.backend.leaderboard.application.LeaderboardService import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.GetMapping -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 +/** + * Exposes authenticated leaderboard endpoints. + * + * @property leaderboardService application service that handles classroom leaderboard lookup + */ @RestController @RequestMapping("/api/v1/leaderboard") -class LeaderboardController ( - +class LeaderboardController( + private val leaderboardService: LeaderboardService, ) { - -} \ No newline at end of file + /** + * Returns the leaderboard for the authenticated user's resolved classroom. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @return ordered leaderboard entries for the resolved classroom + */ + @GetMapping + fun getLeaderboard( + @AuthenticationPrincipal currentUser: CurrentUser, + ): LeaderboardResponse = + leaderboardService.getClassLeaderboardList(currentUser.subject).toLeaderboardResponse() +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardResponse.kt new file mode 100644 index 00000000..1e4501d4 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/api/LeaderboardResponse.kt @@ -0,0 +1,39 @@ +package edu.ntnu.idi.idatt.backend.leaderboard.api + +import java.time.Instant + +/** + * Response payload for a classroom leaderboard. + * + * @property entries ordered leaderboard rows for the resolved classroom + */ +data class LeaderboardResponse( + val entries: List, +) + +/** + * Public leaderboard row exposed to clients. + * + * @property rank one-based position in the ordered leaderboard + * @property pupilUserId persisted pupil id for the row + * @property displayName pupil display name shown in the product + * @property totalScore total accumulated score within the classroom + * @property totalXp total accumulated XP within the classroom + * @property currentLevel current level reached by the pupil + * @property completedStopsCount number of completed stops + * @property completedTasksCount number of completed tasks + * @property finalBossCompleted whether the final boss has been completed + * @property lastActivityAt timestamp of the latest tracked classroom activity + */ +data class LeaderboardEntryResponse( + val rank: Int, + val pupilUserId: Long, + val displayName: String, + val totalScore: Int, + val totalXp: Int, + val currentLevel: Int, + val completedStopsCount: Int, + val completedTasksCount: Int, + val finalBossCompleted: Boolean, + val lastActivityAt: Instant, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt index 4b8941b4..284a67cd 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt @@ -1,8 +1,8 @@ package edu.ntnu.idi.idatt.backend.leaderboard.application -import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import edu.ntnu.idi.idatt.backend.users.profile.infrastructure.PupilProfileRepository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -17,6 +17,7 @@ import org.springframework.transaction.annotation.Transactional class LeaderboardService( private val pupilGameProgressRepository: PupilGameProgressRepository, private val currentUserResolver: CurrentUserResolver, + private val pupilProfileRepository: PupilProfileRepository, ) { /** @@ -28,10 +29,48 @@ class LeaderboardService( * @return classroom leaderboard entries ordered by rank */ @Transactional(readOnly = true) - fun getClassLeaderboardList(authenticatedSubject: String): List { + fun getClassLeaderboardList(authenticatedSubject: String): List { val classroom = currentUserResolver.getClassroomByUser(authenticatedSubject) - return pupilGameProgressRepository + val progressEntries = pupilGameProgressRepository .findAllByClassroom_IdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc(classroom.id) + + val pupilUserIds = progressEntries.mapNotNull { it.pupil?.id }.toSet() + val displayNamesByUserId = pupilProfileRepository.findAllByUserIdIn(pupilUserIds) + .associateBy({ requireNotNull(it.userId) { "Pupil profile is missing user id" } }, { it.displayName }) + + return progressEntries.mapIndexed { index, progress -> + val pupil = requireNotNull(progress.pupil) { "Leaderboard row is missing pupil relation" } + val pupilUserId = requireNotNull(pupil.id) { "Leaderboard row pupil is missing id" } + + LeaderboardEntry( + rank = index + 1, + pupilUserId = pupilUserId, + displayName = displayNamesByUserId[pupilUserId] ?: pupil.username ?: "Unknown pupil", + totalScore = progress.totalScore, + totalXp = progress.totalXp, + currentLevel = progress.currentLevel, + completedStopsCount = progress.completedStopsCount, + completedTasksCount = progress.completedTasksCount, + finalBossCompleted = progress.finalBossCompleted, + lastActivityAt = progress.lastActivityAt, + ) + } } } + +/** + * Internal leaderboard row projection enriched with pupil profile data. + */ +data class LeaderboardEntry( + val rank: Int, + val pupilUserId: Long, + val displayName: String, + val totalScore: Int, + val totalXp: Int, + val currentLevel: Int, + val completedStopsCount: Int, + val completedTasksCount: Int, + val finalBossCompleted: Boolean, + val lastActivityAt: java.time.Instant, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/profile/infrastructure/PupilProfileRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/profile/infrastructure/PupilProfileRepository.kt index d71ed3ed..9befd76c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/profile/infrastructure/PupilProfileRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/profile/infrastructure/PupilProfileRepository.kt @@ -6,4 +6,9 @@ import org.springframework.data.jpa.repository.JpaRepository /** * Repository for pupil profile persistence. */ -interface PupilProfileRepository : JpaRepository +interface PupilProfileRepository : JpaRepository { + /** + * Finds all pupil profiles for the given user ids. + */ + fun findAllByUserIdIn(userIds: Collection): List +} From 25b83c863e466f27fb852b025772c4c6029052b4 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 10:48:39 +0200 Subject: [PATCH 19/24] Revert "Merge in map-stops branch" Signed-off-by: sindrelm --- .../backend/bootstrap/DevDataBootstrap.kt | 3 - .../backend/bootstrap/MapStopBootstrap.kt | 103 ------ .../classroom/application/ClassroomService.kt | 4 - .../application/PupilJoinedClassroomEvent.kt | 9 - .../game/mapStops/api/MapStopApiMappings.kt | 49 --- .../mapStops/api/MapStopOverviewResponse.kt | 28 -- .../game/mapStops/api/MapStopsController.kt | 55 ---- .../api/PupilStopProgressController.kt | 89 ------ .../game/mapStops/api/StopProgressResponse.kt | 27 -- .../mapStops/api/UpdateStopProgressRequest.kt | 19 -- .../mapStops/application/MapStopService.kt | 139 -------- .../PupilProgressSeedingEventListener.kt | 31 -- .../PupilProgressSeedingService.kt | 71 ---- .../application/PupilStopProgressService.kt | 100 ------ .../application/UpdateStopProgressCommand.kt | 18 -- .../backend/game/mapStops/domain/MapStops.kt | 37 --- .../game/mapStops/domain/PupilStopProgress.kt | 73 ----- .../infrastructure/MapStopsRepository.kt | 15 - .../PupilStopProgressRepository.kt | 21 -- .../db/migration/V8__create_map_stops.sql | 33 -- .../backend/classroom/ClassroomServiceTest.kt | 5 +- .../game/mapStops/MapStopServiceTests.kt | 278 ---------------- .../PupilProgressSeedingServiceTests.kt | 163 ---------- .../mapStops/PupilStopProgressServiceTests.kt | 302 ------------------ 24 files changed, 1 insertion(+), 1671 deletions(-) delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt delete mode 100644 src/main/resources/db/migration/V8__create_map_stops.sql delete mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt delete mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt delete mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt index cf5e815d..4827d9d5 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt @@ -44,7 +44,6 @@ class DevDataBootstrap( private val userAvatarRepository: UserAvatarRepository, private val refreshTokenRepository: RefreshTokenRepository, private val passwordEncoder: PasswordEncoder, - private val mapStopBootstrap: MapStopBootstrap ) : ApplicationRunner { private val logger = LoggerFactory.getLogger(javaClass) @@ -103,8 +102,6 @@ class DevDataBootstrap( Instant.now().minus(1, ChronoUnit.HOURS), ) - mapStopBootstrap.seedAllMapStops() - logger.info( "Development bootstrap ensured sample rows for users, profiles, refresh tokens, and classroom {} with join code {}", sampleClassroom.title, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt deleted file mode 100644 index e8aaabb2..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MapStopBootstrap.kt +++ /dev/null @@ -1,103 +0,0 @@ -package edu.ntnu.idi.idatt.backend.bootstrap - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository -import org.springframework.stereotype.Component - -@Component -class MapStopBootstrap( - private val mapStopRepository: MapStopsRepository, -) { - - fun seedAllMapStops() { - seedMapStop( - slug = "nyhetskvartalet", - title = "Nyhetskvartalet", - description = "Nyhetskvartalet", - category = "stop", - displayOrder = 1, - maxScore = 100 - ) - - seedMapStop( - slug = "fotografen", - title = "Fotografen", - description = "Fotografen", - category = "stop", - displayOrder = 2, - maxScore = 100 - ) - - seedMapStop( - slug = "postkontoret", - title = "Postkontoret", - description = "Postkontoret", - category = "stop", - displayOrder = 3, - maxScore = 100 - ) - - seedMapStop( - slug = "markedsplassen", - title = "Markedsplassen", - description = "Markedsplassen", - category = "stop", - displayOrder = 4, - maxScore = 100 - ) - - seedMapStop( - slug = "den-sosiale-markedsplassen", - title = "Den Sosiale Markedsplassen", - description = "Den Sosiale Markedsplassen", - category = "stop", - displayOrder = 5, - maxScore = 100 - ) - - seedMapStop( - slug = "passordbanken", - title = "Passordbanken", - description = "Passordbanken", - category = "stop", - displayOrder = 6, - maxScore = 100 - ) - - seedMapStop( - slug = "datasenteret", - title = "Datasenteret", - description = "Datasenteret", - category = "stop", - displayOrder = 7, - maxScore = 100, - isFinalBoss = true - ) - } - - fun seedMapStop( - slug: String, - title: String, - description: String? = null, - category: String? = null, - displayOrder: Int, - maxScore: Int, - isFinalBoss: Boolean = false, - isActive: Boolean = true, - ) { - if (mapStopRepository.existsBySlug(slug)) return - - mapStopRepository.save( - MapStops( - slug = slug, - title = title, - description = description, - category = category, - displayOrder = displayOrder, - maxScore = maxScore, - isFinalBoss = isFinalBoss, - isActive = isActive, - ), - ) - } -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index b7ece387..51d5ef17 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -2,9 +2,7 @@ package edu.ntnu.idi.idatt.backend.classroom.application import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository -import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilProgressSeedingService import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver -import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -21,7 +19,6 @@ import java.util.* class ClassroomService( private val classroomRepository: ClassroomRepository, private val currentUserResolver: CurrentUserResolver, - private val eventPublisher: ApplicationEventPublisher, ) { /** * Adds an authenticated pupil to a classroom as a pending member. @@ -48,7 +45,6 @@ class ClassroomService( classroom.addPupilMembership(user) classroomRepository.save(classroom) - eventPublisher.publishEvent(PupilJoinedClassroomEvent(pupil = user, classroom = classroom)) return JoinClassroomResult( classroomId = classroom.id, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt deleted file mode 100644 index 2d1001e8..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt +++ /dev/null @@ -1,9 +0,0 @@ -package edu.ntnu.idi.idatt.backend.classroom.application - -import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom -import edu.ntnu.idi.idatt.backend.iam.domain.User - -data class PupilJoinedClassroomEvent( - val pupil: User, - val classroom: Classroom, -) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt deleted file mode 100644 index 82e38a13..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopApiMappings.kt +++ /dev/null @@ -1,49 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.api - -import edu.ntnu.idi.idatt.backend.game.mapStops.application.MapStopOverviewEntry -import edu.ntnu.idi.idatt.backend.game.mapStops.application.UpdateStopProgressCommand -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress - -/** - * Converts a [PupilStopProgress] domain entity to the public [StopProgressResponse] payload. - */ -fun PupilStopProgress.toStopProgressResponse(): StopProgressResponse = - StopProgressResponse( - pupilUserId = id.pupilUserId, - classroomId = id.classroomId, - stopId = id.stopId, - status = status, - currentTaskId = currentTaskId, - bestScore = bestScore, - medalAwarded = medalAwarded, - completedAt = completedAt, - ) - -/** - * Converts an [UpdateStopProgressRequest] HTTP payload to the [UpdateStopProgressCommand] - * consumed by the application layer. - */ -fun UpdateStopProgressRequest.toCommand(): UpdateStopProgressCommand = - UpdateStopProgressCommand( - status = status, - currentTaskId = currentTaskId, - bestScore = bestScore, - medalAwarded = medalAwarded, - ) - -/** - * Converts a [MapStopOverviewEntry] application result to the public [MapStopOverviewResponse] - * payload. - */ -fun MapStopOverviewEntry.toResponse(): MapStopOverviewResponse = - MapStopOverviewResponse( - stopId = stopId, - slug = slug, - title = title, - category = category, - displayOrder = displayOrder, - isFinalBoss = isFinalBoss, - status = status, - stars = stars, - medalAwarded = medalAwarded, - ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt deleted file mode 100644 index 547a2e01..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopOverviewResponse.kt +++ /dev/null @@ -1,28 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.api - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus - -/** - * Response payload for a single map stop enriched with the pupil's progress. - * - * @property stopId unique identifier of the map stop - * @property slug URL-safe kebab-case identifier - * @property title display title of the stop - * @property category category the stop belongs to - * @property displayOrder position of the stop in the ordered map list - * @property isFinalBoss whether this stop is the final boss stop - * @property status current progress status for the authenticated pupil - * @property stars number of stars earned, derived from bestScore vs maxScore - * @property medalAwarded whether a medal has been awarded for this stop - */ -data class MapStopOverviewResponse( - val stopId: Long, - val slug: String?, - val title: String?, - val category: String?, - val displayOrder: Int, - val isFinalBoss: Boolean, - val status: StopProgressStatus, - val stars: Int, - val medalAwarded: Boolean, -) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt deleted file mode 100644 index 032406be..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/MapStopsController.kt +++ /dev/null @@ -1,55 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.api - -import edu.ntnu.idi.idatt.backend.game.mapStops.application.MapStopService -import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser -import org.springframework.security.core.annotation.AuthenticationPrincipal -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.PathVariable -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RestController - -/** - * Exposes endpoints for retrieving map stops and the aggregated map overview for a pupil. - * - * @property mapStopService application service that handles map stop lookups and overview aggregation - */ -@RestController -@RequestMapping("/api/v1/classrooms/{classroomId}/map-stops") -class MapStopsController( - private val mapStopService: MapStopService, -) { - /** - * Returns all active map stops enriched with the pupil's progress, stars, and lock state, - * sorted by display order. - * - * @param currentUser authenticated principal resolved from the JWT access token - * @param classroomId classroom to scope the progress lookup to - * @return sorted list of stops with progress state for the authenticated pupil - */ - @GetMapping - fun getMapOverview( - @AuthenticationPrincipal currentUser: CurrentUser, - @PathVariable classroomId: Long, - ): List = - mapStopService - .getMapOverview(currentUser.subject.toLong(), classroomId) - .map { it.toResponse() } - - /** - * Returns a single active map stop by its URL slug, enriched with the pupil's progress. - * - * @param currentUser authenticated principal resolved from the JWT access token - * @param classroomId classroom to scope the progress lookup to - * @param slug kebab-case slug of the map stop title - * @return map stop matching the given slug with progress state for the authenticated pupil - */ - @GetMapping("/{slug}") - fun getMapStopBySlug( - @AuthenticationPrincipal currentUser: CurrentUser, - @PathVariable classroomId: Long, - @PathVariable slug: String, - ): MapStopOverviewResponse = - mapStopService - .getMapStopOverviewBySlug(currentUser.subject.toLong(), classroomId, slug) - .toResponse() -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt deleted file mode 100644 index 5aa79153..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/PupilStopProgressController.kt +++ /dev/null @@ -1,89 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.api - -import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilStopProgressService -import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser -import jakarta.validation.Valid -import org.springframework.security.access.prepost.PreAuthorize -import org.springframework.security.core.annotation.AuthenticationPrincipal -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.PatchMapping -import org.springframework.web.bind.annotation.PathVariable -import org.springframework.web.bind.annotation.RequestBody -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RestController - -/** - * Exposes endpoints for reading and updating a pupil's progress across map stops. - * - * @property progressService application service that handles progress lookup and state transitions - */ -@RestController -@RequestMapping("/api/v1/classrooms/{classroomId}/pupils/{pupilUserId}/stop-progress") -class PupilStopProgressController( - private val progressService: PupilStopProgressService, -) { - /** - * Returns all stop progress records for a pupil in a classroom. - * Accessible by the pupil themselves or a teacher. - * - * @param currentUser authenticated principal resolved from the JWT access token - * @param classroomId classroom to scope the lookup to - * @param pupilUserId pupil whose progress to retrieve - * @return list of progress records for all stops in the classroom - */ - @GetMapping - @PreAuthorize("hasRole('TEACHER') or #pupilUserId == authentication.principal.subjectAsLong") - fun getAllProgress( - @AuthenticationPrincipal currentUser: CurrentUser, - @PathVariable classroomId: Long, - @PathVariable pupilUserId: Long, - ): List = - progressService - .getProgressForPupil(pupilUserId, classroomId) - .map { it.toStopProgressResponse() } - - /** - * Returns progress for a single stop for a pupil in a classroom. - * Accessible by the pupil themselves or a teacher. - * - * @param currentUser authenticated principal resolved from the JWT access token - * @param classroomId classroom to scope the lookup to - * @param pupilUserId pupil whose progress to retrieve - * @param stopId map stop to retrieve progress for - * @return progress record for the given stop - */ - @GetMapping("/{stopId}") - @PreAuthorize("hasRole('TEACHER') or #pupilUserId == authentication.principal.subjectAsLong") - fun getStopProgress( - @AuthenticationPrincipal currentUser: CurrentUser, - @PathVariable classroomId: Long, - @PathVariable pupilUserId: Long, - @PathVariable stopId: Long, - ): StopProgressResponse = - progressService - .getProgressForStop(pupilUserId, classroomId, stopId) - .toStopProgressResponse() - - /** - * Updates progress for a single stop. Only the pupil themselves may update their own progress. - * - * @param currentUser authenticated principal resolved from the JWT access token - * @param classroomId classroom to scope the update to - * @param pupilUserId pupil whose progress to update - * @param stopId map stop to update progress for - * @param request progress update payload - * @return updated progress record - */ - @PatchMapping("/{stopId}") - @PreAuthorize("#pupilUserId == authentication.principal.subjectAsLong") - fun updateStopProgress( - @AuthenticationPrincipal currentUser: CurrentUser, - @PathVariable classroomId: Long, - @PathVariable pupilUserId: Long, - @PathVariable stopId: Long, - @Valid @RequestBody request: UpdateStopProgressRequest, - ): StopProgressResponse = - progressService - .updateProgress(pupilUserId, classroomId, stopId, request.toCommand()) - .toStopProgressResponse() -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt deleted file mode 100644 index 93830861..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/StopProgressResponse.kt +++ /dev/null @@ -1,27 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.api - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import java.time.Instant - -/** - * Response payload for a pupil's progress on a single map stop. - * - * @property pupilUserId pupil this progress record belongs to - * @property classroomId classroom this progress is scoped to - * @property stopId map stop this progress tracks - * @property status current progress status - * @property currentTaskId current task the pupil is on, or null - * @property bestScore highest score achieved at this stop - * @property medalAwarded whether a medal has been awarded - * @property completedAt timestamp of completion, or null if not yet completed - */ -data class StopProgressResponse( - val pupilUserId: Long, - val classroomId: Long, - val stopId: Long, - val status: StopProgressStatus, - val currentTaskId: Long?, - val bestScore: Int, - val medalAwarded: Boolean, - val completedAt: Instant?, -) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt deleted file mode 100644 index 4d12bbfc..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/api/UpdateStopProgressRequest.kt +++ /dev/null @@ -1,19 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.api - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import jakarta.validation.constraints.Min - -/** - * Request payload for updating a pupil's progress on a single map stop. - * - * @property status new status to transition to, must follow valid state machine transitions - * @property currentTaskId current task the pupil is working on within this stop - * @property bestScore pupil's best score, only persisted if higher than the existing value - * @property medalAwarded whether a medal has been awarded for this stop - */ -data class UpdateStopProgressRequest( - val status: StopProgressStatus?, - val currentTaskId: Long?, - @field:Min(0) val bestScore: Int?, - val medalAwarded: Boolean?, -) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt deleted file mode 100644 index 6546847d..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/MapStopService.kt +++ /dev/null @@ -1,139 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.application - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository -import org.springframework.http.HttpStatus -import org.springframework.stereotype.Service -import org.springframework.web.server.ResponseStatusException - -/** - * Application service that handles map stop lookups and map overview aggregation. - * - * @property mapStopsRepository JPA repository for map stop records - * @property pupilStopProgressRepository JPA repository for pupil stop progress records - */ -@Service -class MapStopService( - private val mapStopsRepository: MapStopsRepository, - private val pupilStopProgressRepository: PupilStopProgressRepository, -) { - /** - * Returns all active map stops sorted by display order. - * - * @return sorted list of active map stops - */ - fun getAllMapStops(): List = - mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc() - - /** - * Returns a single active map stop by its URL slug. - * - * @param slug kebab-case slug to look up - * @return matching map stop - * @throws ResponseStatusException 404 if no stop matches the slug - */ - fun getMapStopBySlug(slug: String): MapStops { - val normalized = slug.replace("-", " ") - return mapStopsRepository.findBySlugIgnoreCase(normalized) - ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "No map stop found for slug: $slug") - } - - /** - * Returns all active map stops enriched with the pupil's progress, stars, and lock state, - * sorted by display order. - * - * @param pupilUserId pupil to retrieve progress for - * @param classroomId classroom to scope the progress lookup to - * @return sorted list of stops with progress state for the pupil - */ - fun getMapOverview(pupilUserId: Long, classroomId: Long): List { - val stops = mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc() - val progressByStopId = pupilStopProgressRepository - .findAllById_PupilUserIdAndId_ClassroomId(pupilUserId, classroomId) - .associateBy { it.id.stopId } - - return stops.mapNotNull { stop -> - val stopId = stop.id ?: return@mapNotNull null - val progress = progressByStopId[stop.id!!] - MapStopOverviewEntry( - stopId = stopId, - slug = stop.slug, - title = stop.title, - category = stop.category, - displayOrder = stop.displayOrder ?: 0, - isFinalBoss = stop.isFinalBoss ?: false, - status = progress?.status ?: StopProgressStatus.LOCKED, - stars = progress?.let { computeStars(it.bestScore, stop.maxScore ?: 0) } ?: 0, - medalAwarded = progress?.medalAwarded ?: false, - ) - } - } - - /** - * Returns a single active map stop by its URL slug, enriched with the pupil's progress. - * - * @param pupilUserId pupil to retrieve progress for - * @param classroomId classroom to scope the progress lookup to - * @param slug kebab-case slug to look up - * @return map stop matching the given slug with progress state for the pupil - * @throws ResponseStatusException 404 if no stop matches the slug - */ - fun getMapStopOverviewBySlug(pupilUserId: Long, classroomId: Long, slug: String): MapStopOverviewEntry { - val stop = getMapStopBySlug(slug) - val stopId = stop.id - ?: throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Map stop has no id") - - val progress = pupilStopProgressRepository - .findById_PupilUserIdAndId_ClassroomIdAndId_StopId(pupilUserId, classroomId, stopId) - - return MapStopOverviewEntry( - stopId = stopId, - slug = stop.slug, - title = stop.title, - category = stop.category, - displayOrder = stop.displayOrder ?: 0, - isFinalBoss = stop.isFinalBoss ?: false, - status = progress?.status ?: StopProgressStatus.LOCKED, - stars = progress?.let { computeStars(it.bestScore, stop.maxScore ?: 0) } ?: 0, - medalAwarded = progress?.medalAwarded ?: false, - ) - } - - private fun computeStars(bestScore: Int, maxScore: Int): Int { - if (maxScore == 0) return 0 - val ratio = bestScore.toDouble() / maxScore - return when { - ratio >= 0.75 -> 3 - ratio >= 0.50 -> 2 - ratio >= 0.25 -> 1 - else -> 0 - } - } -} - -/** - * Aggregated view of a map stop enriched with a pupil's current progress state. - * - * @property stopId unique identifier of the map stop - * @property slug URL-safe kebab-case identifier - * @property title display title of the stop - * @property category category the stop belongs to - * @property displayOrder position in the ordered map list - * @property isFinalBoss whether this stop is the final boss stop - * @property status current progress status for the pupil - * @property stars stars earned, derived from bestScore vs maxScore - * @property medalAwarded whether a medal has been awarded for this stop - */ -data class MapStopOverviewEntry( - val stopId: Long, - val slug: String?, - val title: String?, - val category: String?, - val displayOrder: Int, - val isFinalBoss: Boolean, - val status: StopProgressStatus, - val stars: Int, - val medalAwarded: Boolean, -) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt deleted file mode 100644 index 23875df9..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingEventListener.kt +++ /dev/null @@ -1,31 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.application - -import edu.ntnu.idi.idatt.backend.classroom.application.PupilJoinedClassroomEvent -import org.springframework.context.event.EventListener -import org.springframework.stereotype.Component - -/** - * Proxy for calling the [PupilProgressSeedingService] when a pupil joins a classroom. - * Listens for the [PupilJoinedClassroomEvent] and calls the seeding service to - * seed progress for the pupil if it doesn't already exist. - */ -@Component -class PupilProgressSeedingEventListener( - private val pupilProgressSeedingService: PupilProgressSeedingService, -) { - /** - * Triggers seedIfAbsent. - * - * @param event a [PupilJoinedClassroomEvent] - */ - @EventListener - fun onPupilJoined(event: PupilJoinedClassroomEvent) { - val pupilId = requireNotNull(event.pupil.id) { "Pupil is missing an id" } - pupilProgressSeedingService.seedIfAbsent( - pupilUserId = pupilId, - classroomId = event.classroom.id, - pupil = event.pupil, - classroom = event.classroom, - ) - } -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt deleted file mode 100644 index a9e18888..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilProgressSeedingService.kt +++ /dev/null @@ -1,71 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.application - -import edu.ntnu.idi.idatt.backend.classroom.application.PupilJoinedClassroomEvent -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository -import org.springframework.context.event.EventListener -import org.springframework.stereotype.Service -import org.springframework.transaction.annotation.Transactional - -/** - * Service responsible for seeding stop progress records when a pupil joins a classroom. - * Ensures every pupil starts with a consistent progress state across all active map stops. - * - * @property mapStopsRepository JPA repository for map stop records - * @property pupilStopProgressRepository JPA repository for pupil stop progress records - */ -@Service -class PupilProgressSeedingService( - private val mapStopsRepository: MapStopsRepository, - private val pupilStopProgressRepository: PupilStopProgressRepository, -) { - - /** - * Seeds progress records for a pupil in a classroom if none exist yet. - * The first stop (lowest display order) is seeded as [StopProgressStatus.NOT_STARTED], - * all remaining stops are seeded as [StopProgressStatus.LOCKED]. - * If progress records already exist for this pupil in this classroom, this is a no-op. - * - * @param pupilUserId pupil to seed progress for - * @param classroomId classroom to scope the seeding to - * @param pupil the [User] entity for the pupil - * @param classroom the [Classroom] entity for the classroom - */ - @Transactional - fun seedIfAbsent( - pupilUserId: Long, - classroomId: Long, - pupil: edu.ntnu.idi.idatt.backend.iam.domain.User, - classroom: edu.ntnu.idi.idatt.backend.classroom.domain.Classroom, - ) { - val alreadySeeded = pupilStopProgressRepository - .findAllById_PupilUserIdAndId_ClassroomId(pupilUserId, classroomId) - .isNotEmpty() - - if (alreadySeeded) return - - val stops = mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc() - if (stops.isEmpty()) return - - val records = stops.mapIndexed { index, stop -> - val stopId = stop.id ?: return@mapIndexed null - PupilStopProgress( - id = PupilStopProgressId( - pupilUserId = pupilUserId, - classroomId = classroomId, - stopId = stopId, - ), - pupil = pupil, - classroom = classroom, - stop = stop, - ).apply { - status = if (index == 0) StopProgressStatus.NOT_STARTED else StopProgressStatus.LOCKED - } - }.filterNotNull() - - pupilStopProgressRepository.saveAll(records) - } -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt deleted file mode 100644 index 3a624b42..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/PupilStopProgressService.kt +++ /dev/null @@ -1,100 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.application - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository -import org.springframework.http.HttpStatus -import org.springframework.stereotype.Service -import org.springframework.transaction.annotation.Transactional -import org.springframework.web.server.ResponseStatusException -import java.time.Instant - -/** - * Application service that handles progress lookup and state transitions for pupil map stops. - * - * @property progressRepository JPA repository for pupil stop progress records - */ -@Service -class PupilStopProgressService( - private val progressRepository: PupilStopProgressRepository, -) { - /** - * Returns all stop progress records for a pupil in a classroom. - * - * @param pupilUserId pupil to retrieve progress for - * @param classroomId classroom to scope the lookup to - * @return list of progress records for all stops - */ - fun getProgressForPupil( - pupilUserId: Long, - classroomId: Long, - ): List = - progressRepository.findAllById_PupilUserIdAndId_ClassroomId(pupilUserId, classroomId) - - /** - * Returns progress for a single stop for a pupil in a classroom. - * - * @param pupilUserId pupil to retrieve progress for - * @param classroomId classroom to scope the lookup to - * @param stopId map stop to retrieve progress for - * @return progress record for the given stop - * @throws ResponseStatusException 404 if no progress record exists - */ - fun getProgressForStop( - pupilUserId: Long, - classroomId: Long, - stopId: Long, - ): PupilStopProgress = - progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId( - pupilUserId, classroomId, stopId, - ) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Progress record not found") - - /** - * Applies a partial update to a pupil's progress on a single stop, enforcing valid state - * machine transitions and only updating bestScore when the new value is higher. - * - * @param pupilUserId pupil whose progress to update - * @param classroomId classroom to scope the update to - * @param stopId map stop to update progress for - * @param command update payload - * @return updated progress record - * @throws ResponseStatusException 422 if the status transition is invalid - */ - @Transactional - fun updateProgress( - pupilUserId: Long, - classroomId: Long, - stopId: Long, - command: UpdateStopProgressCommand, - ): PupilStopProgress { - val progress = getProgressForStop(pupilUserId, classroomId, stopId) - - command.status?.let { - validateTransition(progress.status, it) - progress.status = it - if (it == StopProgressStatus.COMPLETED && progress.completedAt == null) { - progress.completedAt = Instant.now() - } - } - command.currentTaskId?.let { progress.currentTaskId = it } - command.bestScore?.let { if (it > progress.bestScore) progress.bestScore = it } - command.medalAwarded?.let { progress.medalAwarded = it } - - return progressRepository.save(progress) - } - - private fun validateTransition(current: StopProgressStatus, next: StopProgressStatus) { - val allowed = mapOf( - StopProgressStatus.LOCKED to setOf(StopProgressStatus.NOT_STARTED), - StopProgressStatus.NOT_STARTED to setOf(StopProgressStatus.IN_PROGRESS), - StopProgressStatus.IN_PROGRESS to setOf(StopProgressStatus.COMPLETED), - StopProgressStatus.COMPLETED to emptySet(), - ) - if (next !in allowed.getValue(current)) { - throw ResponseStatusException( - HttpStatus.UNPROCESSABLE_ENTITY, - "Invalid status transition: $current → $next", - ) - } - } -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt deleted file mode 100644 index 8ae3d052..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/application/UpdateStopProgressCommand.kt +++ /dev/null @@ -1,18 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.application - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus - -/** - * Command for updating a pupil's progress on a single map stop. - * - * @property status new status to transition to, must follow valid state machine transitions - * @property currentTaskId current task the pupil is working on within this stop - * @property bestScore pupil's best score, only persisted if higher than the existing value - * @property medalAwarded whether a medal has been awarded for this stop - */ -data class UpdateStopProgressCommand( - val status: StopProgressStatus?, - val currentTaskId: Long?, - val bestScore: Int?, - val medalAwarded: Boolean?, -) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt deleted file mode 100644 index a4e3eaca..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/MapStops.kt +++ /dev/null @@ -1,37 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.domain - -import jakarta.persistence.Column -import jakarta.persistence.Entity -import jakarta.persistence.GeneratedValue -import jakarta.persistence.GenerationType -import jakarta.persistence.Id -import jakarta.persistence.Table - -/** - * A map-stop representation - */ -@Entity -@Table(name = "map_stops") -class MapStops ( - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - var id: Long? = null, - @Column(length = 255) - var slug: String? = null, - @Column(length = 255) - var title: String? = null, - @Column(length = 255) - var description: String? = null, - @Column(length = 255) - var category: String? = null, - @Column(name = "display_order") - var displayOrder: Int? = null, - @Column(name = "max_score") - var maxScore: Int? = null, - @Column(name="is_final_boss") - var isFinalBoss: Boolean? = false, - @Column(name = "is_active") - var isActive: Boolean? = false, -) { - -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt deleted file mode 100644 index 3bd0ebcb..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/domain/PupilStopProgress.kt +++ /dev/null @@ -1,73 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.domain - -import edu.ntnu.idi.idatt.backend.iam.domain.User -import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom -import jakarta.persistence.Column -import jakarta.persistence.EmbeddedId -import jakarta.persistence.Entity -import jakarta.persistence.EnumType -import jakarta.persistence.Enumerated -import jakarta.persistence.FetchType -import jakarta.persistence.JoinColumn -import jakarta.persistence.ManyToOne -import jakarta.persistence.MapsId -import jakarta.persistence.Table -import jakarta.persistence.Embeddable -import java.io.Serializable -import java.time.Instant - -@Entity -@Table(name = "pupil_stop_progress") -class PupilStopProgress( - - @EmbeddedId - val id: PupilStopProgressId, - - @ManyToOne(fetch = FetchType.LAZY) - @MapsId("pupilUserId") - @JoinColumn(name = "pupil_user_id") - val pupil: User, - - @ManyToOne(fetch = FetchType.LAZY) - @MapsId("classroomId") - @JoinColumn(name = "classroom_id") - val classroom: Classroom, - - @ManyToOne(fetch = FetchType.LAZY) - @MapsId("stopId") - @JoinColumn(name = "stop_id") - val stop: MapStops, -) { - @Enumerated(EnumType.STRING) - @Column(nullable = false) - var status: StopProgressStatus = StopProgressStatus.NOT_STARTED - - @Column - var currentTaskId: Long? = null - - @Column(nullable = false) - var bestScore: Int = 0 - - @Column(nullable = false) - var medalAwarded: Boolean = false - - @Column - var completedAt: Instant? = null -} - -enum class StopProgressStatus { - LOCKED, - NOT_STARTED, - IN_PROGRESS, - COMPLETED, -} - -@Embeddable -data class PupilStopProgressId( - @Column(name = "pupil_user_id") - val pupilUserId: Long, - @Column(name = "classroom_id") - val classroomId: Long, - @Column(name = "stop_id") - val stopId: Long, -) : Serializable \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt deleted file mode 100644 index 609d9b8b..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/MapStopsRepository.kt +++ /dev/null @@ -1,15 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository - -@Repository -interface MapStopsRepository : JpaRepository { - - fun existsBySlug(slug: String): Boolean - - fun findAllByIsActiveTrueOrderByDisplayOrderAsc(): List - - fun findBySlugIgnoreCase(slug: String): MapStops? -} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt deleted file mode 100644 index 385e919b..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/infrastructure/PupilStopProgressRepository.kt +++ /dev/null @@ -1,21 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure - -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId -import org.springframework.data.jpa.repository.JpaRepository -import org.springframework.stereotype.Repository - -@Repository -interface PupilStopProgressRepository : JpaRepository { - - fun findAllById_PupilUserIdAndId_ClassroomId( - pupilUserId: Long, - classroomId: Long, - ): List - - fun findById_PupilUserIdAndId_ClassroomIdAndId_StopId( - pupilUserId: Long, - classroomId: Long, - stopId: Long, - ): PupilStopProgress? -} \ No newline at end of file diff --git a/src/main/resources/db/migration/V8__create_map_stops.sql b/src/main/resources/db/migration/V8__create_map_stops.sql deleted file mode 100644 index b396fa02..00000000 --- a/src/main/resources/db/migration/V8__create_map_stops.sql +++ /dev/null @@ -1,33 +0,0 @@ -CREATE TABLE map_stops ( - id BIGINT NOT NULL AUTO_INCREMENT, - slug VARCHAR(255), - title VARCHAR(255), - description VARCHAR(255), - category VARCHAR(255), - display_order INT, - max_score INT, - is_final_boss BOOLEAN NOT NULL DEFAULT FALSE, - is_active BOOLEAN NOT NULL DEFAULT FALSE, - CONSTRAINT pk_map_stops PRIMARY KEY (id), - CONSTRAINT uk_map_stops_slug UNIQUE (slug) -); - -CREATE TABLE pupil_stop_progress ( - pupil_user_id BIGINT NOT NULL, - classroom_id BIGINT NOT NULL, - stop_id BIGINT NOT NULL, - status ENUM('LOCKED', 'NOT_STARTED', 'IN_PROGRESS', 'COMPLETED') NOT NULL DEFAULT 'LOCKED', - current_task_id BIGINT, - best_score INT NOT NULL DEFAULT 0, - medal_awarded BOOLEAN NOT NULL DEFAULT FALSE, - completed_at DATETIME(6), - CONSTRAINT pk_pupil_stop_progress PRIMARY KEY (pupil_user_id, classroom_id, stop_id), - CONSTRAINT fk_psp_pupil - FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, - CONSTRAINT fk_psp_classroom - FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE, - CONSTRAINT fk_psp_stop - FOREIGN KEY (stop_id) REFERENCES map_stops (id) ON DELETE CASCADE -); - -CREATE INDEX idx_psp_pupil_classroom ON pupil_stop_progress (pupil_user_id, classroom_id); \ No newline at end of file diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index 67343e1e..0f885642 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -20,7 +20,6 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.Mockito.`when` -import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException @@ -28,14 +27,12 @@ class ClassroomServiceTest { private lateinit var classroomRepository: ClassroomRepository private lateinit var currentUserResolver: CurrentUserResolver private lateinit var classroomService: ClassroomService - private lateinit var eventPublisher: ApplicationEventPublisher @BeforeEach fun setup() { classroomRepository = mock(ClassroomRepository::class.java) currentUserResolver = mock(CurrentUserResolver::class.java) - eventPublisher = mock(ApplicationEventPublisher::class.java) - classroomService = ClassroomService(classroomRepository, currentUserResolver, eventPublisher) + classroomService = ClassroomService(classroomRepository, currentUserResolver) } @Test diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt deleted file mode 100644 index dd82bcd5..00000000 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/MapStopServiceTests.kt +++ /dev/null @@ -1,278 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops - -import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom -import edu.ntnu.idi.idatt.backend.game.mapStops.application.MapStopService -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository -import edu.ntnu.idi.idatt.backend.iam.domain.User -import edu.ntnu.idi.idatt.backend.iam.domain.UserRole -import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertThrows -import org.mockito.Mockito -import org.springframework.http.HttpStatus -import org.springframework.web.server.ResponseStatusException - -class MapStopServiceTests { - - @Test - fun `get all map stops returns active stops in display order`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stops = listOf(mapStop(id = 1L, displayOrder = 1), mapStop(id = 2L, displayOrder = 2)) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(stops) - - val result = service.getAllMapStops() - - assertEquals(2, result.size) - assertEquals(1, result[0].displayOrder) - assertEquals(2, result[1].displayOrder) - } - - @Test - fun `get all map stops returns empty list when no active stops exist`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) - - val result = service.getAllMapStops() - - assertEquals(0, result.size) - } - - @Test - fun `get map stop by slug returns matching stop after normalising dashes to spaces`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 1L, slug = "data center") - - Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(stop) - - val result = service.getMapStopBySlug("data-center") - - assertEquals(stop, result) - } - - @Test - fun `get map stop by slug throws 404 when no stop matches`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - - Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("not a stop")).thenReturn(null) - - val exception = assertThrows { - service.getMapStopBySlug("not-a-stop") - } - - assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) - } - - @Test - fun `get map overview falls back to LOCKED when pupil has no progress record for a stop`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 10L, displayOrder = 1) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) - - val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) - - assertEquals(1, result.size) - assertEquals(StopProgressStatus.LOCKED, result[0].status) - assertEquals(0, result[0].stars) - assertEquals(false, result[0].medalAwarded) - } - - @Test - fun `get map overview reflects pupil progress status and stars when record exists`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 10L, displayOrder = 1, maxScore = 100) - val progress = progress(stopId = 10L, status = StopProgressStatus.COMPLETED, bestScore = 80) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) - - val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) - - assertEquals(StopProgressStatus.COMPLETED, result[0].status) - assertEquals(3, result[0].stars) // 80/100 = 0.80 ≥ 0.75 → 3 stars - } - - @Test - fun `get map overview returns empty list when there are no active stops`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) - - val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) - - assertEquals(0, result.size) - } - - @Test - fun `get map stop overview by slug returns enriched entry for pupil with progress`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 5L, slug = "data center", maxScore = 100) - val progress = progress(stopId = 5L, status = StopProgressStatus.IN_PROGRESS, bestScore = 50) - - Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(stop) - Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 5L)) - .thenReturn(progress) - - val result = service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") - - assertEquals(5L, result.stopId) - assertEquals(StopProgressStatus.IN_PROGRESS, result.status) - assertEquals(2, result.stars) // 50/100 = 0.50 ≥ 0.50 → 2 stars - } - - @Test - fun `get map stop overview by slug falls back to LOCKED when pupil has no progress`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 5L, slug = "data center") - - Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(stop) - Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 5L)) - .thenReturn(null) - - val result = service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") - - assertEquals(StopProgressStatus.LOCKED, result.status) - assertEquals(0, result.stars) - } - - @Test - fun `get map stop overview by slug throws 404 for unknown slug`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - - Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(null) - - val exception = assertThrows { - service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") - } - - assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) - } - - @Test - fun `get map overview awards 0 stars when best score is below 25 percent of max`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 1L, maxScore = 100) - val progress = progress(stopId = 1L, bestScore = 24) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) - - assertEquals(0, service.getMapOverview(1L, 2L)[0].stars) - } - - @Test - fun `get map overview awards 1 star when best score is exactly 25 percent of max`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 1L, maxScore = 100) - val progress = progress(stopId = 1L, bestScore = 25) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) - - assertEquals(1, service.getMapOverview(1L, 2L)[0].stars) - } - - @Test - fun `get map overview awards 2 stars when best score is exactly 50 percent of max`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 1L, maxScore = 100) - val progress = progress(stopId = 1L, bestScore = 50) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) - - assertEquals(2, service.getMapOverview(1L, 2L)[0].stars) - } - - @Test - fun `get map overview awards 0 stars when max score is zero`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) - val stop = mapStop(id = 1L, maxScore = 0) - val progress = progress(stopId = 1L, bestScore = 100) - - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(listOf(progress)) - - assertEquals(0, service.getMapOverview(1L, 2L)[0].stars) - } - - private fun mapStop( - id: Long, - slug: String? = "stop $id", - displayOrder: Int = 1, - maxScore: Int = 100, - ) = MapStops().apply { - this.id = id - this.slug = slug - this.title = "Stop $id" - this.category = "test" - this.displayOrder = displayOrder - this.maxScore = maxScore - this.isFinalBoss = false - this.isActive = true - } - - private fun progress( - stopId: Long, - status: StopProgressStatus = StopProgressStatus.NOT_STARTED, - bestScore: Int = 0, - medalAwarded: Boolean = false, - ): PupilStopProgress { - val pupil = User( - id = 1L, - username = "pupil-one", - passwordHash = "hash", - role = UserRole.PUPIL, - status = UserStatus.ACTIVE, - ) - val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") - return PupilStopProgress( - id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), - pupil = pupil, - classroom = classroom, - stop = mapStop(id = stopId), - ).apply { - this.status = status - this.bestScore = bestScore - this.medalAwarded = medalAwarded - } - } -} \ No newline at end of file diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt deleted file mode 100644 index a2ae1c3b..00000000 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilProgressSeedingServiceTests.kt +++ /dev/null @@ -1,163 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops - -import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom -import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilProgressSeedingService -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.MapStopsRepository -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository -import edu.ntnu.idi.idatt.backend.iam.domain.User -import edu.ntnu.idi.idatt.backend.iam.domain.UserRole -import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Test -import org.mockito.ArgumentCaptor -import org.mockito.Mockito -import org.mockito.Mockito.never -import org.mockito.Mockito.verify - -class PupilProgressSeedingServiceTests { - - @Test - fun `seed if absent is a no-op when progress records already exist for the pupil`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) - val (pupil, classroom) = pupilAndClassroom() - - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)) - .thenReturn(listOf(existingProgress(stopId = 1L))) - - service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) - - verify(progressRepository, never()).saveAll(Mockito.anyList()) - } - - @Test - fun `seed if absent is a no-op when there are no active map stops`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) - val (pupil, classroom) = pupilAndClassroom() - - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) - - service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) - - verify(progressRepository, never()).saveAll(Mockito.anyList()) - } - - @Test - fun `seed if absent seeds first stop as NOT_STARTED and remaining stops as LOCKED`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) - val (pupil, classroom) = pupilAndClassroom() - val stops = listOf(mapStop(id = 1L), mapStop(id = 2L), mapStop(id = 3L)) - - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(stops) - - @Suppress("UNCHECKED_CAST") - val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> - Mockito.`when`(progressRepository.saveAll(captor.capture())).thenReturn(emptyList()) - - service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) - - val saved = captor.value - assertEquals(3, saved.size) - assertEquals(StopProgressStatus.NOT_STARTED, saved[0].status) - assertEquals(StopProgressStatus.LOCKED, saved[1].status) - assertEquals(StopProgressStatus.LOCKED, saved[2].status) - } - - @Test - fun `seed if absent seeds exactly one stop as NOT_STARTED when only one active stop exists`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) - val (pupil, classroom) = pupilAndClassroom() - - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()) - .thenReturn(listOf(mapStop(id = 1L))) - - @Suppress("UNCHECKED_CAST") - val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> - Mockito.`when`(progressRepository.saveAll(captor.capture())).thenReturn(emptyList()) - - service.seedIfAbsent(pupilUserId = 1L, classroomId = 2L, pupil = pupil, classroom = classroom) - - val saved = captor.value - assertEquals(1, saved.size) - assertEquals(StopProgressStatus.NOT_STARTED, saved[0].status) - } - - @Test - fun `seed if absent assigns correct pupil and classroom ids on seeded records`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilProgressSeedingService(mapStopsRepository, progressRepository) - val (pupil, classroom) = pupilAndClassroom(pupilId = 7L, classroomId = 99L) - - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(7L, 99L)).thenReturn(emptyList()) - Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()) - .thenReturn(listOf(mapStop(id = 1L), mapStop(id = 2L))) - - @Suppress("UNCHECKED_CAST") - val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> - Mockito.`when`(progressRepository.saveAll(captor.capture())).thenReturn(emptyList()) - - service.seedIfAbsent(pupilUserId = 7L, classroomId = 99L, pupil = pupil, classroom = classroom) - - val saved = captor.value - assertEquals(7L, saved[0].id.pupilUserId) - assertEquals(99L, saved[0].id.classroomId) - assertEquals(1L, saved[0].id.stopId) - assertEquals(7L, saved[1].id.pupilUserId) - assertEquals(99L, saved[1].id.classroomId) - assertEquals(2L, saved[1].id.stopId) - } - - private data class PupilAndClassroom(val pupil: User, val classroom: Classroom) - - private fun pupilAndClassroom(pupilId: Long = 1L, classroomId: Long = 2L): PupilAndClassroom { - val pupil = User( - id = pupilId, - username = "pupil-$pupilId", - passwordHash = "hash", - role = UserRole.PUPIL, - status = UserStatus.ACTIVE, - ) - val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") - return PupilAndClassroom(pupil, classroom) - } - - private fun mapStop(id: Long, displayOrder: Int = id.toInt()) = MapStops().apply { - this.id = id - this.slug = "stop-$id" - this.title = "Stop $id" - this.displayOrder = displayOrder.toInt() - this.isActive = true - } - - private fun existingProgress(stopId: Long): PupilStopProgress { - val pupil = User( - id = 1L, - username = "pupil-one", - passwordHash = "hash", - role = UserRole.PUPIL, - status = UserStatus.ACTIVE, - ) - val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") - return PupilStopProgress( - id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), - pupil = pupil, - classroom = classroom, - stop = mapStop(id = stopId), - ) - } -} \ No newline at end of file diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt deleted file mode 100644 index 96b7934d..00000000 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapStops/PupilStopProgressServiceTests.kt +++ /dev/null @@ -1,302 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapStops - -import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom -import edu.ntnu.idi.idatt.backend.game.mapStops.application.PupilStopProgressService -import edu.ntnu.idi.idatt.backend.game.mapStops.application.UpdateStopProgressCommand -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.MapStops -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgress -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.PupilStopProgressId -import edu.ntnu.idi.idatt.backend.game.mapStops.domain.StopProgressStatus -import edu.ntnu.idi.idatt.backend.game.mapStops.infrastructure.PupilStopProgressRepository -import edu.ntnu.idi.idatt.backend.iam.domain.User -import edu.ntnu.idi.idatt.backend.iam.domain.UserRole -import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNotNull -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertThrows -import org.mockito.ArgumentMatchers.any -import org.mockito.Mockito -import org.springframework.http.HttpStatus -import org.springframework.web.server.ResponseStatusException - -class PupilStopProgressServiceTests { - - @Test - fun `get progress for pupil returns all progress records for given pupil and classroom`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val records = listOf(progress(stopId = 1L), progress(stopId = 2L)) - - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(records) - - val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) - - assertEquals(2, result.size) - } - - @Test - fun `get progress for pupil returns empty list when pupil has no records in classroom`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - - Mockito.`when`(progressRepository.findAllById_PupilUserIdAndId_ClassroomId(1L, 2L)).thenReturn(emptyList()) - - val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) - - assertEquals(0, result.size) - } - - @Test - fun `get progress for stop returns record when it exists`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 3L) - - Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 3L)) - .thenReturn(record) - - val result = service.getProgressForStop(pupilUserId = 1L, classroomId = 2L, stopId = 3L) - - assertEquals(record, result) - } - - @Test - fun `get progress for stop throws 404 when no record exists`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - - Mockito.`when`(progressRepository.findById_PupilUserIdAndId_ClassroomIdAndId_StopId(1L, 2L, 99L)) - .thenReturn(null) - - val exception = assertThrows { - service.getProgressForStop(pupilUserId = 1L, classroomId = 2L, stopId = 99L) - } - - assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) - } - - @Test - fun `update progress transitions from LOCKED to NOT_STARTED`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, status = StopProgressStatus.LOCKED) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = StopProgressStatus.NOT_STARTED, null, null, null), - ) - - assertEquals(StopProgressStatus.NOT_STARTED, result.status) - } - - @Test - fun `update progress transitions from NOT_STARTED to IN_PROGRESS`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = StopProgressStatus.IN_PROGRESS, null, null, null), - ) - - assertEquals(StopProgressStatus.IN_PROGRESS, result.status) - } - - @Test - fun `update progress transitions from IN_PROGRESS to COMPLETED and sets completedAt`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), - ) - - assertEquals(StopProgressStatus.COMPLETED, result.status) - assertNotNull(result.completedAt) - } - - @Test - fun `update progress does not overwrite completedAt when stop is already completed`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) - - stubFindAndSave(progressRepository, record) - - // first completion - service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), - ) - val firstCompletedAt = record.completedAt - - // attempt second completion — already COMPLETED so transition is rejected anyway, - // but we also verify completedAt is not touched if it were somehow reached - assertNotNull(firstCompletedAt) - } - - @Test - fun `update progress rejects invalid transition from COMPLETED`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, status = StopProgressStatus.COMPLETED) - - stubFind(progressRepository, record) - - val exception = assertThrows { - service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = StopProgressStatus.IN_PROGRESS, null, null, null), - ) - } - - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, exception.statusCode) - } - - @Test - fun `update progress rejects skipping from NOT_STARTED directly to COMPLETED`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) - - stubFind(progressRepository, record) - - val exception = assertThrows { - service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), - ) - } - - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, exception.statusCode) - } - - @Test - fun `update progress persists higher best score`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, bestScore = 40) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = 80, medalAwarded = null), - ) - - assertEquals(80, result.bestScore) - } - - @Test - fun `update progress does not overwrite best score when new value is lower`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, bestScore = 90) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = 50, medalAwarded = null), - ) - - assertEquals(90, result.bestScore) - } - - @Test - fun `update progress sets current task id`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = null, currentTaskId = 7L, bestScore = null, medalAwarded = null), - ) - - assertEquals(7L, result.currentTaskId) - } - - @Test - fun `update progress awards medal when medal flag is set`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = null, medalAwarded = true), - ) - - assertEquals(true, result.medalAwarded) - } - - @Test - fun `update progress with all null fields changes nothing`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = PupilStopProgressService(progressRepository) - val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, bestScore = 55) - - stubFindAndSave(progressRepository, record) - - val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, - command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = null, medalAwarded = null), - ) - - assertEquals(StopProgressStatus.IN_PROGRESS, result.status) - assertEquals(55, result.bestScore) - assertNull(result.completedAt) - } - - private fun progress( - stopId: Long, - status: StopProgressStatus = StopProgressStatus.NOT_STARTED, - bestScore: Int = 0, - ): PupilStopProgress { - val pupil = User( - id = 1L, - username = "pupil-one", - passwordHash = "hash", - role = UserRole.PUPIL, - status = UserStatus.ACTIVE, - ) - val stop = MapStops().apply { id = stopId } - val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") - return PupilStopProgress( - id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), - pupil = pupil, - classroom = classroom, - stop = stop, - ).apply { - this.status = status - this.bestScore = bestScore - } - } - - private fun stubFind(repo: PupilStopProgressRepository, record: PupilStopProgress) { - Mockito.`when`(repo.findById_PupilUserIdAndId_ClassroomIdAndId_StopId( - record.id.pupilUserId, record.id.classroomId, record.id.stopId, - )).thenReturn(record) - } - - private fun stubFindAndSave(repo: PupilStopProgressRepository, record: PupilStopProgress) { - stubFind(repo, record) - Mockito.`when`(repo.save(any(PupilStopProgress::class.java))).thenAnswer { it.arguments[0] } - } -} \ No newline at end of file From 478ecc9c58cc7b6a72b7c8795f4cd9c89275dc04 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 11:22:04 +0200 Subject: [PATCH 20/24] Create PupilGameProgress entry when a pupil joins a classroom Signed-off-by: sindrelm --- .../classroom/application/ClassroomService.kt | 14 +++++++++++++ .../classroom/ClassroomIntegrationTests.kt | 21 +++++++++++++++++++ .../backend/classroom/ClassroomServiceTest.kt | 13 +++++++++++- 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index 51d5ef17..853c23b2 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -2,6 +2,9 @@ package edu.ntnu.idi.idatt.backend.classroom.application import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgressId +import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver import org.springframework.http.HttpStatus import org.springframework.stereotype.Service @@ -19,6 +22,7 @@ import java.util.* class ClassroomService( private val classroomRepository: ClassroomRepository, private val currentUserResolver: CurrentUserResolver, + private val pupilGameProgressRepository: PupilGameProgressRepository, ) { /** * Adds an authenticated pupil to a classroom as a pending member. @@ -45,6 +49,16 @@ class ClassroomService( classroom.addPupilMembership(user) classroomRepository.save(classroom) + pupilGameProgressRepository.save( + PupilGameProgress( + id = PupilGameProgressId( + pupilUserId = userId, + classroomId = classroom.id, + ), + pupil = user, + classroom = classroom, + ), + ) return JoinClassroomResult( classroomId = classroom.id, diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt index 83ca65eb..013a1bad 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.json.JsonMapper import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus @@ -39,6 +40,9 @@ class ClassroomIntegrationTests { @Autowired private lateinit var classroomRepository: ClassroomRepository + @Autowired + private lateinit var pupilGameProgressRepository: PupilGameProgressRepository + @Autowired private lateinit var refreshTokenRepository: RefreshTokenRepository @@ -63,6 +67,7 @@ class ClassroomIntegrationTests { fun setUp() { refreshTokenRepository.deleteAll() classroomRepository.deleteAll() + pupilGameProgressRepository.deleteAll() userAvatarRepository.deleteAll() pupilProfileRepository.deleteAll() teacherProfileRepository.deleteAll() @@ -106,6 +111,14 @@ class ClassroomIntegrationTests { requireNotNull(pupil.id), ) ?: 0 assertEquals(1, membershipCount) + + val progressCount = jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM pupil_game_progress WHERE classroom_id = ? AND pupil_user_id = ?", + Int::class.java, + classroom.id, + requireNotNull(pupil.id), + ) ?: 0 + assertEquals(1, progressCount) } @Test @@ -132,6 +145,14 @@ class ClassroomIntegrationTests { "padding-check", ) ?: 0 assertEquals(1, membershipCount) + + val progressCount = jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM pupil_game_progress pgp JOIN users u ON u.id = pgp.pupil_user_id WHERE pgp.classroom_id = (SELECT id FROM classrooms WHERE join_code = ?) AND u.username = ?", + Int::class.java, + "CLASS42", + "padding-check", + ) ?: 0 + assertEquals(1, progressCount) } @Test diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index 0f885642..f77d12d9 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -8,6 +8,8 @@ import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomPupilMembershipId import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomPupilStatus import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress +import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole @@ -26,13 +28,15 @@ import org.springframework.web.server.ResponseStatusException class ClassroomServiceTest { private lateinit var classroomRepository: ClassroomRepository private lateinit var currentUserResolver: CurrentUserResolver + private lateinit var pupilGameProgressRepository: PupilGameProgressRepository private lateinit var classroomService: ClassroomService @BeforeEach fun setup() { classroomRepository = mock(ClassroomRepository::class.java) currentUserResolver = mock(CurrentUserResolver::class.java) - classroomService = ClassroomService(classroomRepository, currentUserResolver) + pupilGameProgressRepository = mock(PupilGameProgressRepository::class.java) + classroomService = ClassroomService(classroomRepository, currentUserResolver, pupilGameProgressRepository) } @Test @@ -52,6 +56,7 @@ class ClassroomServiceTest { assertEquals("class", result.classroomTitle) assertEquals("PENDING", result.membershipStatus) verify(classroomRepository).save(classroom) + verify(pupilGameProgressRepository).save(any(PupilGameProgress::class.java)) verify(classroomRepository).findByJoinCode(classroomCode) } @@ -71,6 +76,7 @@ class ClassroomServiceTest { assertEquals(HttpStatus.CONFLICT, exception.statusCode) verify(classroomRepository, never()).save(classroom) + verify(pupilGameProgressRepository, never()).save(any(PupilGameProgress::class.java)) } @Test @@ -86,6 +92,7 @@ class ClassroomServiceTest { classroomService.joinClassroom(command) } assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + verify(pupilGameProgressRepository, never()).save(any(PupilGameProgress::class.java)) } @Test @@ -111,6 +118,7 @@ class ClassroomServiceTest { } assertEquals(HttpStatus.CONFLICT, exception.statusCode) + verify(pupilGameProgressRepository, never()).save(any(PupilGameProgress::class.java)) } @Test @@ -131,6 +139,7 @@ class ClassroomServiceTest { assertEquals(HttpStatus.FORBIDDEN, exception.statusCode) verify(classroomRepository, never()).save(classroom) + verify(pupilGameProgressRepository, never()).save(any(PupilGameProgress::class.java)) } @Test @@ -151,6 +160,7 @@ class ClassroomServiceTest { assertEquals(HttpStatus.FORBIDDEN, exception.statusCode) verify(classroomRepository, never()).save(classroom) + verify(pupilGameProgressRepository, never()).save(any(PupilGameProgress::class.java)) } @Test @@ -165,6 +175,7 @@ class ClassroomServiceTest { } assertEquals(HttpStatus.UNAUTHORIZED, exception.statusCode) + verify(pupilGameProgressRepository, never()).save(any(PupilGameProgress::class.java)) } @Test From 1425a579cb95de7739c9f547658315099cbddb37 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 11:25:11 +0200 Subject: [PATCH 21/24] Remove spacing Signed-off-by: sindrelm --- .../game/gameProgress/domain/PupilGameProgress.kt | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt index f2b7d8fc..d3a1e3aa 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/domain/PupilGameProgress.kt @@ -30,35 +30,26 @@ import java.time.Instant class PupilGameProgress( @EmbeddedId var id: PupilGameProgressId = PupilGameProgressId(), - @ManyToOne(fetch = FetchType.LAZY, optional = false) @MapsId("pupilUserId") @JoinColumn(name = "pupil_user_id", nullable = false) var pupil: User? = null, - @ManyToOne(fetch = FetchType.LAZY, optional = false) @MapsId("classroomId") @JoinColumn(name = "classroom_id", nullable = false) var classroom: Classroom? = null, - @Column(name = "total_score", nullable = false) var totalScore: Int = 0, - @Column(name = "total_xp", nullable = false) var totalXp: Int = 0, - @Column(name = "current_level", nullable = false) var currentLevel: Int = 1, - @Column(name = "completed_stops_count", nullable = false) var completedStopsCount: Int = 0, - @Column(name = "completed_tasks_count", nullable = false) var completedTasksCount: Int = 0, - @Column(name = "final_boss_completed", nullable = false) var finalBossCompleted: Boolean = false, - @Column(name = "last_activity_at", nullable = false) var lastActivityAt: Instant = Instant.now(), ) { @@ -91,7 +82,6 @@ class PupilGameProgress( data class PupilGameProgressId( @Column(name = "pupil_user_id") val pupilUserId: Long = 0, - @Column(name = "classroom_id") val classroomId: Long = 0, ) : Serializable From 77c682846427e903b20247fe5be5c984eb4dbc6d Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 11:27:04 +0200 Subject: [PATCH 22/24] Fix test Signed-off-by: sindrelm --- .../edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index f77d12d9..fec70e4f 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -18,6 +18,7 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.verify From fa6ce39de8f8e1c8e564ebcea2c56c9a704d8e96 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 11:29:47 +0200 Subject: [PATCH 23/24] Add bootstrap data in PupilGameProgress table Signed-off-by: sindrelm --- .../backend/bootstrap/DevDataBootstrap.kt | 109 +++++++++++++++++- 1 file changed, 103 insertions(+), 6 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt index 4827d9d5..c2a46d85 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt @@ -1,8 +1,12 @@ package edu.ntnu.idi.idatt.backend.bootstrap import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomPupilStatus import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress +import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgressId +import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository import edu.ntnu.idi.idatt.backend.iam.domain.RefreshToken import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole @@ -43,6 +47,7 @@ class DevDataBootstrap( private val pupilProfileRepository: PupilProfileRepository, private val userAvatarRepository: UserAvatarRepository, private val refreshTokenRepository: RefreshTokenRepository, + private val pupilGameProgressRepository: PupilGameProgressRepository, private val passwordEncoder: PasswordEncoder, ) : ApplicationRunner { private val logger = LoggerFactory.getLogger(javaClass) @@ -70,17 +75,41 @@ class DevDataBootstrap( role = UserRole.PUPIL, ) - seedTeacherProfile(teacher, "Ada Lunde", "Trondheim Montessori") - seedPupilProfile(pupilAda, "Ada", 101) - seedPupilProfile(pupilNoah, "Noah", null) - seedPupilAvatar(pupilAda) - seedPupilAvatar(pupilNoah) val sampleClassroom = seedClassroom( ownerTeacher = teacher, title = "Mysterieklubben 5A", description = "Eksempelklasserom for lokal utvikling", joinCode = "CLASS42", ) + seedTeacherProfile(teacher, "Ada Lunde", "Trondheim Montessori") + seedPupilProfile(pupilAda, "Ada", sampleClassroom.id) + seedPupilProfile(pupilNoah, "Noah", sampleClassroom.id) + seedPupilAvatar(pupilAda) + seedPupilAvatar(pupilNoah) + seedClassroomMembership(sampleClassroom, pupilAda) + seedClassroomMembership(sampleClassroom, pupilNoah) + seedPupilGameProgress( + pupil = pupilAda, + classroom = sampleClassroom, + totalScore = 240, + totalXp = 480, + currentLevel = 4, + completedStopsCount = 3, + completedTasksCount = 9, + finalBossCompleted = false, + lastActivityAt = Instant.now().minus(2, ChronoUnit.HOURS), + ) + seedPupilGameProgress( + pupil = pupilNoah, + classroom = sampleClassroom, + totalScore = 125, + totalXp = 260, + currentLevel = 2, + completedStopsCount = 1, + completedTasksCount = 5, + finalBossCompleted = false, + lastActivityAt = Instant.now().minus(1, ChronoUnit.DAYS), + ) seedRefreshToken(admin, "dev-admin-refresh-token", Instant.now().plus(14, ChronoUnit.DAYS), null) seedRefreshToken( @@ -165,7 +194,9 @@ class DevDataBootstrap( currentClassroomId: Long?, ) { val userId = requireNotNull(user.id) { "Pupil seed user must have an id" } - if (pupilProfileRepository.existsById(userId)) { + pupilProfileRepository.findById(userId).ifPresent { existingProfile -> + existingProfile.displayName = displayName + existingProfile.currentClassroomId = currentClassroomId return } @@ -178,6 +209,72 @@ class DevDataBootstrap( ) } + private fun seedClassroomMembership( + classroom: Classroom, + pupil: User, + ) { + val pupilUserId = requireNotNull(pupil.id) { "Pupil seed user must have an id" } + val existingMembership = classroom.pupilMemberships.firstOrNull { it.id.pupilUserId == pupilUserId } + if (existingMembership != null) { + existingMembership.status = ClassroomPupilStatus.ACTIVE + existingMembership.approvedAt = Instant.now() + return + } + + classroom.addPupilMembership(pupil) + classroom.pupilMemberships.first { it.id.pupilUserId == pupilUserId }.apply { + status = ClassroomPupilStatus.ACTIVE + approvedAt = Instant.now() + } + classroomRepository.save(classroom) + } + + private fun seedPupilGameProgress( + pupil: User, + classroom: Classroom, + totalScore: Int, + totalXp: Int, + currentLevel: Int, + completedStopsCount: Int, + completedTasksCount: Int, + finalBossCompleted: Boolean, + lastActivityAt: Instant, + ) { + val pupilUserId = requireNotNull(pupil.id) { "Pupil seed user must have an id" } + val classroomId = classroom.id + val existingProgress = pupilGameProgressRepository.findByPupil_IdAndClassroom_Id(pupilUserId, classroomId) + if (existingProgress != null) { + existingProgress.updateProgress( + totalScore = totalScore, + totalXp = totalXp, + currentLevel = currentLevel, + completedStopsCount = completedStopsCount, + completedTasksCount = completedTasksCount, + finalBossCompleted = finalBossCompleted, + lastActivityAt = lastActivityAt, + ) + return + } + + pupilGameProgressRepository.save( + PupilGameProgress( + id = PupilGameProgressId( + pupilUserId = pupilUserId, + classroomId = classroomId, + ), + pupil = pupil, + classroom = classroom, + totalScore = totalScore, + totalXp = totalXp, + currentLevel = currentLevel, + completedStopsCount = completedStopsCount, + completedTasksCount = completedTasksCount, + finalBossCompleted = finalBossCompleted, + lastActivityAt = lastActivityAt, + ), + ) + } + private fun seedPupilAvatar(user: User) { val userId = requireNotNull(user.id) { "Pupil seed user must have an id" } if (userAvatarRepository.existsById(userId)) { From 702ab8da8dc23a563ac461d11af965a4ca034761 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Mon, 20 Apr 2026 13:22:15 +0200 Subject: [PATCH 24/24] Remove underscores from func names Signed-off-by: sindrelm --- .../edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt | 2 +- .../infrastructure/PupilGameProgressRepository.kt | 4 ++-- .../backend/leaderboard/application/LeaderboardService.kt | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt index 7f521e73..8a73b33a 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt @@ -246,7 +246,7 @@ class DevDataBootstrap( ) { val pupilUserId = requireNotNull(pupil.id) { "Pupil seed user must have an id" } val classroomId = classroom.id - val existingProgress = pupilGameProgressRepository.findByPupil_IdAndClassroom_Id(pupilUserId, classroomId) + val existingProgress = pupilGameProgressRepository.findByPupilIdAndClassroom_Id(pupilUserId, classroomId) if (existingProgress != null) { existingProgress.updateProgress( totalScore = totalScore, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt index d6e03b2f..91f37f49 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/gameProgress/infrastructure/PupilGameProgressRepository.kt @@ -15,7 +15,7 @@ interface PupilGameProgressRepository : JpaRepository } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt index 284a67cd..4810ca09 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/leaderboard/application/LeaderboardService.kt @@ -33,7 +33,7 @@ class LeaderboardService( val classroom = currentUserResolver.getClassroomByUser(authenticatedSubject) val progressEntries = pupilGameProgressRepository - .findAllByClassroom_IdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc(classroom.id) + .findAllByClassroomIdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc(classroom.id) val pupilUserIds = progressEntries.mapNotNull { it.pupil?.id }.toSet() val displayNamesByUserId = pupilProfileRepository.findAllByUserIdIn(pupilUserIds)