From 1875765ee120dcc09abed6c6da9dd79d087a0399 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:20:40 +0200 Subject: [PATCH 01/15] migration --- .../migration/V16__create_medals_tables.sql | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/resources/db/migration/V16__create_medals_tables.sql diff --git a/src/main/resources/db/migration/V16__create_medals_tables.sql b/src/main/resources/db/migration/V16__create_medals_tables.sql new file mode 100644 index 00000000..9ab9b725 --- /dev/null +++ b/src/main/resources/db/migration/V16__create_medals_tables.sql @@ -0,0 +1,29 @@ +CREATE TABLE medals ( + id BIGINT NOT NULL AUTO_INCREMENT, + code VARCHAR(100) NOT NULL, + title VARCHAR(255) NOT NULL, + description TEXT, + medal_type ENUM('STOP_COMPLETION', 'EXAMPLE_APPROVAL') NOT NULL, + stop_id BIGINT, + icon_url VARCHAR(255), + CONSTRAINT pk_medals PRIMARY KEY (id), + CONSTRAINT uk_medals_code UNIQUE (code), + CONSTRAINT fk_medals_stop FOREIGN KEY (stop_id) REFERENCES map_stops (id) ON DELETE SET NULL +); + +CREATE TABLE pupil_medals ( + id BIGINT NOT NULL AUTO_INCREMENT, + pupil_user_id BIGINT NOT NULL, + classroom_id BIGINT NOT NULL, + medal_id BIGINT NOT NULL, + awarded_reason VARCHAR(255), + awarded_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + CONSTRAINT pk_pupil_medals PRIMARY KEY (id), + CONSTRAINT fk_pupil_medals_pupil FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_pupil_medals_classroom FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE, + CONSTRAINT fk_pupil_medals_medal FOREIGN KEY (medal_id) REFERENCES medals (id) ON DELETE CASCADE +); + +CREATE INDEX idx_pupil_medals_pupil_user ON pupil_medals (pupil_user_id); +CREATE INDEX idx_pupil_medals_classroom ON pupil_medals (classroom_id); +CREATE INDEX idx_pupil_medals_medal ON pupil_medals (medal_id); From 772aa6d64fcad799e0bc420d909a31106fe043a8 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:21:01 +0200 Subject: [PATCH 02/15] models --- .../idatt/backend/game/medals/domain/Medal.kt | 43 +++++++++++++++++++ .../backend/game/medals/domain/MedalType.kt | 6 +++ .../backend/game/medals/domain/PupilMedal.kt | 42 ++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/Medal.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/MedalType.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/Medal.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/Medal.kt new file mode 100644 index 00000000..280cd12d --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/Medal.kt @@ -0,0 +1,43 @@ +package edu.ntnu.idi.idatt.backend.game.medals.domain + +import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop +import jakarta.persistence.* + +/** + * Represents a medal that can be earned by a pupil. + * + * @property id Unique identifier for the medal. + * @property code Unique code identifying the medal (e.g., "stop-1-completion"). + * @property title Human-readable title of the medal. + * @property description Detailed description of how to earn the medal. + * @property medalType The type of medal (e.g., [MedalType.STOP_COMPLETION]). + * @property stop The map stop associated with this medal, if any. + * @property iconUrl URL to the icon representing the medal. + */ +@Entity +@Table(name = "medals") +class Medal( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + val id: Long = 0, + + @Column(nullable = false, unique = true) + val code: String, + + @Column(nullable = false) + val title: String, + + @Column + val description: String?, + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + val medalType: MedalType, + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "stop_id") + val stop: MapStop?, + + @Column + val iconUrl: String? +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/MedalType.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/MedalType.kt new file mode 100644 index 00000000..8388aeb8 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/MedalType.kt @@ -0,0 +1,6 @@ +package edu.ntnu.idi.idatt.backend.game.medals.domain + +enum class MedalType { + STOP_COMPLETION, + EXAMPLE_APPROVAL +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt new file mode 100644 index 00000000..04818aeb --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt @@ -0,0 +1,42 @@ +package edu.ntnu.idi.idatt.backend.game.medals.domain + +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import jakarta.persistence.* +import java.time.Instant + +/** + * Represents a medal earned by a pupil within a specific classroom. + * + * @property id Unique identifier for the award record. + * @property pupil The pupil who earned the medal. + * @property classroom The classroom context in which the medal was earned. + * @property medal The medal that was awarded. + * @property awardedReason Reason why the medal was awarded. + * @property awardedAt The timestamp when the medal was awarded. + */ +@Entity +@Table(name = "pupil_medals") +class PupilMedal( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + val id: Long = 0, + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "pupil_user_id", nullable = false) + val pupil: User, + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "classroom_id", nullable = false) + val classroom: Classroom, + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "medal_id", nullable = false) + val medal: Medal, + + @Column + val awardedReason: String?, + + @Column(nullable = false) + val awardedAt: Instant = Instant.now() +) From d4bad6c0346426685a383c5c4b74d2918191703a Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:29:07 +0200 Subject: [PATCH 03/15] implement service and repository for medals --- .../game/medals/application/MedalService.kt | 40 +++++++++++++++++++ .../game/medals/repository/MedalRepository.kt | 11 +++++ .../medals/repository/PupilMedalRepository.kt | 12 ++++++ 3 files changed, 63 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt new file mode 100644 index 00000000..f77171f0 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt @@ -0,0 +1,40 @@ +package edu.ntnu.idi.idatt.backend.game.medals.application + +import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal +import edu.ntnu.idi.idatt.backend.game.medals.repository.MedalRepository +import edu.ntnu.idi.idatt.backend.game.medals.repository.PupilMedalRepository +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import java.util.stream.Collectors + +@Service +class MedalService( + private val medalRepository: MedalRepository, + private val pupilMedalRepository: PupilMedalRepository +) { + @Transactional(readOnly = true) + fun getAllMedals(): List = medalRepository.findAll() + + @Transactional(readOnly = true) + fun getPupilMedals(pupil: User, classroom: Classroom): List { + return pupilMedalRepository.findAllByPupilUserIdAndClassroomId(pupil.id, classroom.id).collect(Collectors.toList()) + } + + @Transactional + fun awardStopMedal(pupil: User, classroom: Classroom, stopId: Long) { + val medal = medalRepository.findByStopId(stopId) ?: return + if (!pupilMedalRepository.existsByPupilUserIdAndClassroomIdAndMedalId(pupil.id, classroom.id, medal.id)) { + pupilMedalRepository.save( + PupilMedal( + pupil = pupil, + classroom = classroom, + medal = medal, + awardedReason = "Completed stop ${medal.title}" + ) + ) + } + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt new file mode 100644 index 00000000..ae104d94 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt @@ -0,0 +1,11 @@ +package edu.ntnu.idi.idatt.backend.game.medals.repository + +import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +@Repository +interface MedalRepository : JpaRepository { + fun findByCode(code: String): Medal? + fun findByStopId(stopId: Long): Medal? +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt new file mode 100644 index 00000000..c7dd26a2 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt @@ -0,0 +1,12 @@ +package edu.ntnu.idi.idatt.backend.game.medals.repository + +import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository +import java.util.stream.Stream + +@Repository +interface PupilMedalRepository : JpaRepository { + fun findAllByPupilUserIdAndClassroomId(pupilUserId: Long, classroomId: Long): Stream + fun existsByPupilUserIdAndClassroomIdAndMedalId(pupilUserId: Long, classroomId: Long, medalId: Long): Boolean +} From eb448e0d1fae1f4790872f65fea40d93f096e708 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:29:25 +0200 Subject: [PATCH 04/15] award medals on stop finished --- .../application/PupilStopProgressService.kt | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) 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 index 5c844634..0ab320c4 100644 --- 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 @@ -9,7 +9,9 @@ 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 +import edu.ntnu.idi.idatt.backend.game.medals.application.MedalService +import edu.ntnu.idi.idatt.backend.iam.repository.UserRepository +import edu.ntnu.idi.idatt.backend.classroom.repository.ClassroomRepository /** * Application service that handles progress lookup and state transitions for pupil map stops. @@ -19,7 +21,10 @@ import java.time.Instant @Service class PupilStopProgressService( private val progressRepository: PupilStopProgressRepository, - private val mapStopRepository: MapStopsRepository + private val mapStopRepository: MapStopsRepository, + private val medalService: MedalService, + private val userRepository: UserRepository, + private val classroomRepository: ClassroomRepository ) { /** * Returns all stop progress records for a pupil in a classroom. @@ -89,6 +94,10 @@ class PupilStopProgressService( if (next == StopProgressStatus.COMPLETED && progress.completedAt == null) { progress.completedAt = Instant.now() unlockNextStop(pupilUserId, classroomId, stopId, activeStops) + + val pupil = userRepository.findById(pupilUserId).orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil not found") } + val classroom = classroomRepository.findById(classroomId).orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") } + medalService.awardStopMedal(pupil, classroom, stopId) } } command.currentTaskId?.let { progress.currentTaskId = it } From dd91a855bbded5550f13ed163b7688aed8cadbde Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:30:09 +0200 Subject: [PATCH 05/15] api for listing medals --- .../game/medals/api/MedalsController.kt | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt new file mode 100644 index 00000000..a5124558 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt @@ -0,0 +1,46 @@ +package edu.ntnu.idi.idatt.backend.game.medals.api + +import edu.ntnu.idi.idatt.backend.game.medals.application.MedalService +import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal +import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import org.springframework.http.HttpStatus +import org.springframework.web.bind.annotation.* +import org.springframework.web.server.ResponseStatusException + +@RestController +@RequestMapping("/api/pupil/medals") +class MedalsController( + private val medalService: MedalService, + private val currentUserResolver: CurrentUserResolver +) { + @GetMapping + fun getMedals(currentUser: CurrentUser): MedalOverviewResponse { + val pupil = currentUserResolver.requirePupil(currentUser.subject) + val classroom = currentUserResolver.getClassroomByUser(currentUser) + + val allMedals = medalService.getAllMedals() + val earnedMedals = medalService.getPupilMedals(pupil, classroom) + + val earnedMedalIds = earnedMedals.map { it.medal.id }.toSet() + + return MedalOverviewResponse( + medals = allMedals.map { medal -> + MedalEntry( + medal = medal, + earned = earnedMedalIds.contains(medal.id) + ) + } + ) + } +} + +data class MedalOverviewResponse( + val medals: List +) + +data class MedalEntry( + val medal: Medal, + val earned: Boolean +) From ff76bd43c4abc6af3856507ed9bd3c0e89e33c1f Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:32:56 +0200 Subject: [PATCH 06/15] add api for info about specific medal --- .../idi/idatt/backend/game/medals/api/MedalsController.kt | 6 ++++++ .../idatt/backend/game/medals/application/MedalService.kt | 3 +++ 2 files changed, 9 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt index a5124558..a37ed2d3 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt @@ -34,6 +34,12 @@ class MedalsController( } ) } + + @GetMapping("/{id}") + fun getMedal(@PathVariable id: Long): Medal { + return medalService.getMedalById(id) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Medal not found") + } } data class MedalOverviewResponse( diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt index f77171f0..58a2c0fb 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt @@ -15,6 +15,9 @@ class MedalService( private val medalRepository: MedalRepository, private val pupilMedalRepository: PupilMedalRepository ) { + @Transactional(readOnly = true) + fun getMedalById(id: Long): Medal? = medalRepository.findById(id).orElse(null) + @Transactional(readOnly = true) fun getAllMedals(): List = medalRepository.findAll() From ef3c80d0207bb359c05ed950f3b3e3b1dc72110e Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 14:35:48 +0200 Subject: [PATCH 07/15] fix failing tests --- .../game/medals/application/MedalService.kt | 39 ++++++++- .../mapstops/PupilStopProgressServiceTests.kt | 83 +++++++++++++++---- 2 files changed, 104 insertions(+), 18 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt index 58a2c0fb..15e7f60c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt @@ -10,26 +10,61 @@ import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.stream.Collectors +/** + * Application service for managing medals and awarding them to pupils. + * + * @property medalRepository Repository for medal definitions + * @property pupilMedalRepository Repository for pupil-earned medals + */ @Service class MedalService( private val medalRepository: MedalRepository, private val pupilMedalRepository: PupilMedalRepository ) { + /** + * Retrieves a medal by its ID. + * + * @param id the ID of the medal to retrieve + * @return the medal if found, or null otherwise + */ @Transactional(readOnly = true) fun getMedalById(id: Long): Medal? = medalRepository.findById(id).orElse(null) + /** + * Retrieves all available medal definitions. + * + * @return a list of all medals + */ @Transactional(readOnly = true) fun getAllMedals(): List = medalRepository.findAll() + /** + * Retrieves all medals earned by a specific pupil in a specific classroom. + * + * @param pupil the pupil whose medals to retrieve + * @param classroom the classroom context + * @return a list of earned medals + */ @Transactional(readOnly = true) fun getPupilMedals(pupil: User, classroom: Classroom): List { - return pupilMedalRepository.findAllByPupilUserIdAndClassroomId(pupil.id, classroom.id).collect(Collectors.toList()) + val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" } + val classroomId = requireNotNull(classroom.id) { "Classroom is missing an id" } + return pupilMedalRepository.findAllByPupilIdAndClassroomId(pupilId, classroomId).collect(Collectors.toList()) } + /** + * Awards a stop-related medal to a pupil if they haven't already earned it. + * + * @param pupil the pupil to award the medal to + * @param classroom the classroom context + * @param stopId the ID of the stop that triggers the medal + */ @Transactional fun awardStopMedal(pupil: User, classroom: Classroom, stopId: Long) { val medal = medalRepository.findByStopId(stopId) ?: return - if (!pupilMedalRepository.existsByPupilUserIdAndClassroomIdAndMedalId(pupil.id, classroom.id, medal.id)) { + val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" } + val classroomId = requireNotNull(classroom.id) { "Classroom is missing an id" } + if (!pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(pupilId, classroomId, medal.id)) { pupilMedalRepository.save( PupilMedal( 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 50bc07da..228668dc 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 @@ -1,17 +1,20 @@ package edu.ntnu.idi.idatt.backend.game.mapstops import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository 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.MapStop 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.medals.application.MedalService 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 edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull @@ -21,6 +24,7 @@ import org.mockito.ArgumentMatchers.any import org.mockito.Mockito import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException +import java.util.Optional class PupilStopProgressServiceTests { @@ -28,7 +32,7 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns all progress records for given pupil and classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val records = listOf(progress(stopId = 1L), progress(stopId = 2L)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(records) @@ -42,7 +46,7 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns empty list when pupil has no records in classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(emptyList()) val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) @@ -54,7 +58,7 @@ class PupilStopProgressServiceTests { fun `get progress for stop returns record when it exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 3L) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 3L)) @@ -69,7 +73,7 @@ class PupilStopProgressServiceTests { fun `get progress for stop throws 404 when no record exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 99L)) .thenReturn(null) @@ -85,7 +89,7 @@ class PupilStopProgressServiceTests { fun `update progress transitions from LOCKED to NOT_STARTED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.LOCKED) stubFindAndSave(progressRepository, record) @@ -102,7 +106,7 @@ class PupilStopProgressServiceTests { fun `update progress transitions from NOT_STARTED to IN_PROGRESS`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFindAndSave(progressRepository, record) @@ -119,7 +123,7 @@ class PupilStopProgressServiceTests { fun `update progress transitions from IN_PROGRESS to COMPLETED and sets completedAt`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -137,7 +141,7 @@ class PupilStopProgressServiceTests { fun `update progress does not overwrite completedAt when stop is already completed`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -158,7 +162,7 @@ class PupilStopProgressServiceTests { fun `update progress rejects invalid transition from COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.COMPLETED) stubFind(progressRepository, record) @@ -177,7 +181,7 @@ class PupilStopProgressServiceTests { fun `update progress rejects skipping from NOT_STARTED directly to COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFind(progressRepository, record) @@ -196,7 +200,7 @@ class PupilStopProgressServiceTests { fun `update progress persists higher best score`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, bestScore = 40) stubFindAndSave(progressRepository, record) @@ -213,7 +217,7 @@ class PupilStopProgressServiceTests { fun `update progress does not overwrite best score when new value is lower`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, bestScore = 90) stubFindAndSave(progressRepository, record) @@ -230,7 +234,7 @@ class PupilStopProgressServiceTests { fun `update progress sets current task id`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -247,7 +251,7 @@ class PupilStopProgressServiceTests { fun `update progress awards medal when medal flag is set`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -264,7 +268,7 @@ class PupilStopProgressServiceTests { fun `update progress with all null fields changes nothing`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, bestScore = 55) stubFindAndSave(progressRepository, record) @@ -314,4 +318,51 @@ class PupilStopProgressServiceTests { stubFind(repo, record) Mockito.`when`(repo.save(any(PupilStopProgress::class.java))).thenAnswer { it.arguments[0] } } -} \ No newline at end of file + + private fun service( + progressRepository: PupilStopProgressRepository, + mapStopRepository: MapStopsRepository, + ): PupilStopProgressService { + val medalService = Mockito.mock(MedalService::class.java) + val userRepository = Mockito.mock(UserRepository::class.java) + val classroomRepository = Mockito.mock(ClassroomRepository::class.java) + + Mockito.`when`(mapStopRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()) + .thenReturn(listOf(mapStop(1L), mapStop(2L), mapStop(3L))) + Mockito.`when`(userRepository.findById(1L)).thenReturn(Optional.of(pupil())) + Mockito.`when`(classroomRepository.findById(2L)).thenReturn(Optional.of(classroom())) + + return PupilStopProgressService( + progressRepository, + mapStopRepository, + medalService, + userRepository, + classroomRepository, + ) + } + + private fun pupil(): User = + User( + id = 1L, + username = "pupil-one", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + + private fun classroom(): Classroom = + Classroom( + id = 2L, + ownerTeacherId = 1L, + title = "Test Classroom", + ) + + private fun mapStop(stopId: Long, displayOrder: Int = stopId.toInt()): MapStop = + MapStop( + id = stopId, + slug = "stop-$stopId", + title = "Stop $stopId", + displayOrder = displayOrder, + isActive = true, + ) +} From 60940d2c7cc6319a37c809b3fa544f35c9fea74a Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 14:35:56 +0200 Subject: [PATCH 08/15] kdocs --- .../application/PupilStopProgressService.kt | 9 ++++-- .../game/medals/api/MedalsController.kt | 30 +++++++++++++++++++ .../game/medals/repository/MedalRepository.kt | 3 ++ .../medals/repository/PupilMedalRepository.kt | 7 +++-- 4 files changed, 45 insertions(+), 4 deletions(-) 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 index 0ab320c4..41529b88 100644 --- 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 @@ -10,13 +10,18 @@ import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import org.springframework.web.server.ResponseStatusException import edu.ntnu.idi.idatt.backend.game.medals.application.MedalService -import edu.ntnu.idi.idatt.backend.iam.repository.UserRepository -import edu.ntnu.idi.idatt.backend.classroom.repository.ClassroomRepository +import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +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 + * @property mapStopRepository Repository for map stop definitions + * @property medalService Service for awarding medals upon stop completion + * @property userRepository Repository for user lookup + * @property classroomRepository Repository for classroom lookup */ @Service class PupilStopProgressService( diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt index a37ed2d3..6fc02959 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt @@ -9,12 +9,24 @@ import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.* import org.springframework.web.server.ResponseStatusException +/** + * API controller for pupil medal operations. + * + * @property medalService Service for managing medal logic + * @property currentUserResolver Resolver for authenticated user and classroom context + */ @RestController @RequestMapping("/api/pupil/medals") class MedalsController( private val medalService: MedalService, private val currentUserResolver: CurrentUserResolver ) { + /** + * Retrieves an overview of all medals and whether the current pupil has earned them. + * + * @param currentUser the authenticated principal + * @return a response containing all medals and their earned status + */ @GetMapping fun getMedals(currentUser: CurrentUser): MedalOverviewResponse { val pupil = currentUserResolver.requirePupil(currentUser.subject) @@ -35,6 +47,13 @@ class MedalsController( ) } + /** + * Retrieves detailed information about a specific medal. + * + * @param id the ID of the medal to retrieve + * @return the medal details + * @throws ResponseStatusException 404 if the medal is not found + */ @GetMapping("/{id}") fun getMedal(@PathVariable id: Long): Medal { return medalService.getMedalById(id) @@ -42,10 +61,21 @@ class MedalsController( } } +/** + * Response containing an overview of medals. + * + * @property medals list of medal entries + */ data class MedalOverviewResponse( val medals: List ) +/** + * An entry in the medal overview, combining medal info with earned status. + * + * @property medal the medal definition + * @property earned whether the pupil has earned this medal + */ data class MedalEntry( val medal: Medal, val earned: Boolean diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt index ae104d94..5aa67708 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt @@ -4,6 +4,9 @@ import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository +/** + * Repository for accessing [Medal] entities. + */ @Repository interface MedalRepository : JpaRepository { fun findByCode(code: String): Medal? diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt index c7dd26a2..1ca0d753 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt @@ -5,8 +5,11 @@ import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import java.util.stream.Stream +/** + * Repository for accessing [PupilMedal] entities. + */ @Repository interface PupilMedalRepository : JpaRepository { - fun findAllByPupilUserIdAndClassroomId(pupilUserId: Long, classroomId: Long): Stream - fun existsByPupilUserIdAndClassroomIdAndMedalId(pupilUserId: Long, classroomId: Long, medalId: Long): Boolean + fun findAllByPupilIdAndClassroomId(pupilId: Long, classroomId: Long): Stream + fun existsByPupilIdAndClassroomIdAndMedalId(pupilId: Long, classroomId: Long, medalId: Long): Boolean } From 2089c0b5d0701062a91b5b2b1fb2db46810f75cf Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 14:39:36 +0200 Subject: [PATCH 09/15] use authenticationprincipal --- .../ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt index 6fc02959..ad3d182a 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt @@ -6,6 +6,7 @@ import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import org.springframework.http.HttpStatus +import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.* import org.springframework.web.server.ResponseStatusException @@ -28,7 +29,7 @@ class MedalsController( * @return a response containing all medals and their earned status */ @GetMapping - fun getMedals(currentUser: CurrentUser): MedalOverviewResponse { + fun getMedals(@AuthenticationPrincipal currentUser: CurrentUser): MedalOverviewResponse { val pupil = currentUserResolver.requirePupil(currentUser.subject) val classroom = currentUserResolver.getClassroomByUser(currentUser) From cda6eda73324cb01bf645b907c44fc59308a6946 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 14:43:52 +0200 Subject: [PATCH 10/15] prevent duplicate medals on resubmissions --- .../game/medals/application/MedalService.kt | 19 ++++-- .../migration/V16__create_medals_tables.sql | 1 + .../backend/game/medals/MedalServiceTests.kt | 64 +++++++++++++++++++ 3 files changed, 77 insertions(+), 7 deletions(-) create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt index 15e7f60c..eb387840 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt @@ -6,6 +6,7 @@ import edu.ntnu.idi.idatt.backend.game.medals.repository.MedalRepository import edu.ntnu.idi.idatt.backend.game.medals.repository.PupilMedalRepository import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.stream.Collectors @@ -65,14 +66,18 @@ class MedalService( val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" } val classroomId = requireNotNull(classroom.id) { "Classroom is missing an id" } if (!pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(pupilId, classroomId, medal.id)) { - pupilMedalRepository.save( - PupilMedal( - pupil = pupil, - classroom = classroom, - medal = medal, - awardedReason = "Completed stop ${medal.title}" + try { + pupilMedalRepository.saveAndFlush( + PupilMedal( + pupil = pupil, + classroom = classroom, + medal = medal, + awardedReason = "Completed stop ${medal.title}" + ) ) - ) + } catch (_: DataIntegrityViolationException) { + // A concurrent completion request may have inserted the same medal first. + } } } } diff --git a/src/main/resources/db/migration/V16__create_medals_tables.sql b/src/main/resources/db/migration/V16__create_medals_tables.sql index 9ab9b725..05f8cd2a 100644 --- a/src/main/resources/db/migration/V16__create_medals_tables.sql +++ b/src/main/resources/db/migration/V16__create_medals_tables.sql @@ -19,6 +19,7 @@ CREATE TABLE pupil_medals ( awarded_reason VARCHAR(255), awarded_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT pk_pupil_medals PRIMARY KEY (id), + CONSTRAINT uk_pupil_medals_pupil_classroom_medal UNIQUE (pupil_user_id, classroom_id, medal_id), CONSTRAINT fk_pupil_medals_pupil FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, CONSTRAINT fk_pupil_medals_classroom FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE, CONSTRAINT fk_pupil_medals_medal FOREIGN KEY (medal_id) REFERENCES medals (id) ON DELETE CASCADE diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt new file mode 100644 index 00000000..11048a6f --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt @@ -0,0 +1,64 @@ +package edu.ntnu.idi.idatt.backend.game.medals + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.game.medals.application.MedalService +import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.game.medals.domain.MedalType +import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal +import edu.ntnu.idi.idatt.backend.game.medals.repository.MedalRepository +import edu.ntnu.idi.idatt.backend.game.medals.repository.PupilMedalRepository +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.assertDoesNotThrow +import org.junit.jupiter.api.Test +import org.mockito.ArgumentMatchers.any +import org.mockito.Mockito +import org.springframework.dao.DataIntegrityViolationException + +class MedalServiceTests { + + @Test + fun `award stop medal ignores duplicate award race`() { + val medalRepository = Mockito.mock(MedalRepository::class.java) + val pupilMedalRepository = Mockito.mock(PupilMedalRepository::class.java) + val service = MedalService(medalRepository, pupilMedalRepository) + + Mockito.`when`(medalRepository.findByStopId(5L)).thenReturn(medal(stopId = 5L)) + Mockito.`when`(pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(1L, 2L, 10L)).thenReturn(false) + Mockito.`when`(pupilMedalRepository.saveAndFlush(any(PupilMedal::class.java))).thenThrow( + DataIntegrityViolationException("duplicate medal award"), + ) + + assertDoesNotThrow { + service.awardStopMedal(pupil(), classroom(), 5L) + } + } + + private fun pupil(): User = + User( + id = 1L, + username = "pupil-one", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + + private fun classroom(): Classroom = + Classroom( + id = 2L, + ownerTeacherId = 9L, + title = "Test Classroom", + ) + + private fun medal(stopId: Long): Medal = + Medal( + id = 10L, + code = "stop-$stopId-completion", + title = "Stop $stopId Complete", + description = "Awarded for completing stop $stopId", + medalType = MedalType.STOP_COMPLETION, + stop = null, + iconUrl = null, + ) +} From 480980c9c20441bab5ff287c471ebe240d1f1925 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Thu, 23 Apr 2026 09:53:53 +0200 Subject: [PATCH 11/15] versioned api --- .../ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt index ad3d182a..64ba75a5 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt @@ -17,7 +17,7 @@ import org.springframework.web.server.ResponseStatusException * @property currentUserResolver Resolver for authenticated user and classroom context */ @RestController -@RequestMapping("/api/pupil/medals") +@RequestMapping("/api/v1/pupil/medals") class MedalsController( private val medalService: MedalService, private val currentUserResolver: CurrentUserResolver From 247ea926961ac9f13cbb9b348682535f1039ad09 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Thu, 23 Apr 2026 09:56:39 +0200 Subject: [PATCH 12/15] fix duplicate award race cond. --- .../game/medals/application/MedalService.kt | 36 +++++++++++++------ .../backend/game/medals/MedalServiceTests.kt | 34 ++++++++++++++++-- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt index eb387840..75b68600 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt @@ -8,7 +8,10 @@ import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service +import org.springframework.transaction.PlatformTransactionManager +import org.springframework.transaction.TransactionDefinition import org.springframework.transaction.annotation.Transactional +import org.springframework.transaction.support.TransactionTemplate import java.util.stream.Collectors /** @@ -20,8 +23,13 @@ import java.util.stream.Collectors @Service class MedalService( private val medalRepository: MedalRepository, - private val pupilMedalRepository: PupilMedalRepository + private val pupilMedalRepository: PupilMedalRepository, + transactionManager: PlatformTransactionManager, ) { + private val awardTransaction = TransactionTemplate(transactionManager).apply { + propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRES_NEW + } + /** * Retrieves a medal by its ID. * @@ -60,23 +68,31 @@ class MedalService( * @param classroom the classroom context * @param stopId the ID of the stop that triggers the medal */ - @Transactional fun awardStopMedal(pupil: User, classroom: Classroom, stopId: Long) { val medal = medalRepository.findByStopId(stopId) ?: return val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" } val classroomId = requireNotNull(classroom.id) { "Classroom is missing an id" } if (!pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(pupilId, classroomId, medal.id)) { try { - pupilMedalRepository.saveAndFlush( - PupilMedal( - pupil = pupil, - classroom = classroom, - medal = medal, - awardedReason = "Completed stop ${medal.title}" + awardTransaction.executeWithoutResult { + pupilMedalRepository.saveAndFlush( + PupilMedal( + pupil = pupil, + classroom = classroom, + medal = medal, + awardedReason = "Completed stop ${medal.title}" + ) ) + } + } catch (exception: DataIntegrityViolationException) { + val alreadyAwarded = pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId( + pupilId, + classroomId, + medal.id, ) - } catch (_: DataIntegrityViolationException) { - // A concurrent completion request may have inserted the same medal first. + if (!alreadyAwarded) { + throw exception + } } } } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt index 11048a6f..dc0ec094 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt @@ -12,9 +12,12 @@ import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import org.junit.jupiter.api.Assertions.assertDoesNotThrow import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows import org.mockito.ArgumentMatchers.any import org.mockito.Mockito import org.springframework.dao.DataIntegrityViolationException +import org.springframework.transaction.PlatformTransactionManager +import org.springframework.transaction.support.SimpleTransactionStatus class MedalServiceTests { @@ -22,10 +25,12 @@ class MedalServiceTests { fun `award stop medal ignores duplicate award race`() { val medalRepository = Mockito.mock(MedalRepository::class.java) val pupilMedalRepository = Mockito.mock(PupilMedalRepository::class.java) - val service = MedalService(medalRepository, pupilMedalRepository) + val service = MedalService(medalRepository, pupilMedalRepository, transactionManager()) Mockito.`when`(medalRepository.findByStopId(5L)).thenReturn(medal(stopId = 5L)) - Mockito.`when`(pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(1L, 2L, 10L)).thenReturn(false) + Mockito.`when`(pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(1L, 2L, 10L)) + .thenReturn(false) + .thenReturn(true) Mockito.`when`(pupilMedalRepository.saveAndFlush(any(PupilMedal::class.java))).thenThrow( DataIntegrityViolationException("duplicate medal award"), ) @@ -35,6 +40,26 @@ class MedalServiceTests { } } + @Test + fun `award stop medal rethrows unexpected integrity failure`() { + val medalRepository = Mockito.mock(MedalRepository::class.java) + val pupilMedalRepository = Mockito.mock(PupilMedalRepository::class.java) + val service = MedalService(medalRepository, pupilMedalRepository, transactionManager()) + val exception = DataIntegrityViolationException("foreign key failure") + + Mockito.`when`(medalRepository.findByStopId(5L)).thenReturn(medal(stopId = 5L)) + Mockito.`when`(pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(1L, 2L, 10L)) + .thenReturn(false) + .thenReturn(false) + Mockito.`when`(pupilMedalRepository.saveAndFlush(any(PupilMedal::class.java))).thenThrow(exception) + + val thrown = assertThrows { + service.awardStopMedal(pupil(), classroom(), 5L) + } + + org.junit.jupiter.api.Assertions.assertSame(exception, thrown) + } + private fun pupil(): User = User( id = 1L, @@ -61,4 +86,9 @@ class MedalServiceTests { stop = null, iconUrl = null, ) + + private fun transactionManager(): PlatformTransactionManager = + Mockito.mock(PlatformTransactionManager::class.java).also { transactionManager -> + Mockito.`when`(transactionManager.getTransaction(any())).thenReturn(SimpleTransactionStatus()) + } } From 622d111bed9d348cbfe00d0d0c5442b17c282d85 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Thu, 23 Apr 2026 10:44:54 +0200 Subject: [PATCH 13/15] seed some medals --- .../backend/bootstrap/DevDataBootstrap.kt | 4 +- .../idatt/backend/bootstrap/MedalBootstrap.kt | 50 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MedalBootstrap.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 b1a4d9c5..8de26d21 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 @@ -56,6 +56,7 @@ class DevDataBootstrap( private val notebookEntryRepository: NotebookEntryRepository, private val passwordEncoder: PasswordEncoder, private val mapStopBootstrap: MapStopBootstrap, + private val medalBootstrap: MedalBootstrap, private val taskBootstrap: TaskBootstrap, private val pupilProgressSeedingService: PupilProgressSeedingService, ) : ApplicationRunner { @@ -141,6 +142,7 @@ class DevDataBootstrap( ) mapStopBootstrap.seedAllMapStops() + medalBootstrap.seedAllMedals() val activeStops = taskBootstrap.seedAllTasks(classroom = sampleClassroom, teacher = teacher) seedNotebookEntries( classroom = sampleClassroom, @@ -423,4 +425,4 @@ class DevDataBootstrap( HexFormat.of().formatHex( MessageDigest.getInstance("SHA-256").digest(rawToken.toByteArray(StandardCharsets.UTF_8)), ) -} \ No newline at end of file +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MedalBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MedalBootstrap.kt new file mode 100644 index 00000000..20d2acbb --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MedalBootstrap.kt @@ -0,0 +1,50 @@ +package edu.ntnu.idi.idatt.backend.bootstrap + +import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.game.medals.domain.MedalType +import edu.ntnu.idi.idatt.backend.game.medals.repository.MedalRepository +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty +import org.springframework.stereotype.Component + +@Component +@ConditionalOnProperty(name = ["app.bootstrap.enabled"], havingValue = "true") +class MedalBootstrap( + private val medalRepository: MedalRepository, + private val mapStopsRepository: MapStopsRepository, +) { + fun seedAllMedals() { + mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc().forEach { stop -> + val stopId = requireNotNull(stop.id) { "Seeded map stop must have an id" } + val slug = requireNotNull(stop.slug) { "Seeded map stop must have a slug" } + val title = requireNotNull(stop.title) { "Seeded map stop must have a title" } + val code = "${slug}-completion" + + if (medalRepository.findByCode(code) == null) { + medalRepository.save( + Medal( + code = code, + title = "$title fullført", + description = "Tildeles når eleven fullfører stop nummer $stopId: $title.", + medalType = MedalType.STOP_COMPLETION, + stop = stop, + iconUrl = null, + ), + ) + } + } + + if (medalRepository.findByCode("example-approval") == null) { + medalRepository.save( + Medal( + code = "example-approval", + title = "Eksempelgodkjenning", + description = "Tildeles når et eksempelinnhold blir godkjent.", + medalType = MedalType.EXAMPLE_APPROVAL, + stop = null, + iconUrl = null, + ), + ) + } + } +} From 94381c13d074f974f84b8eaf14262c61be250161 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Thu, 23 Apr 2026 11:36:43 +0200 Subject: [PATCH 14/15] rename migration --- ...16__create_medals_tables.sql => V17__create_medals_tables.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/main/resources/db/migration/{V16__create_medals_tables.sql => V17__create_medals_tables.sql} (100%) diff --git a/src/main/resources/db/migration/V16__create_medals_tables.sql b/src/main/resources/db/migration/V17__create_medals_tables.sql similarity index 100% rename from src/main/resources/db/migration/V16__create_medals_tables.sql rename to src/main/resources/db/migration/V17__create_medals_tables.sql From ef0d61840334495d8f12d09e3a45da82097c3ffc Mon Sep 17 00:00:00 2001 From: eilifhl Date: Thu, 23 Apr 2026 13:15:18 +0200 Subject: [PATCH 15/15] remove awardedreason --- .../idi/idatt/backend/game/medals/application/MedalService.kt | 1 - .../ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt | 4 ---- src/main/resources/db/migration/V17__create_medals_tables.sql | 1 - 3 files changed, 6 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt index 75b68600..b053efac 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt @@ -80,7 +80,6 @@ class MedalService( pupil = pupil, classroom = classroom, medal = medal, - awardedReason = "Completed stop ${medal.title}" ) ) } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt index 04818aeb..81452755 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt @@ -12,7 +12,6 @@ import java.time.Instant * @property pupil The pupil who earned the medal. * @property classroom The classroom context in which the medal was earned. * @property medal The medal that was awarded. - * @property awardedReason Reason why the medal was awarded. * @property awardedAt The timestamp when the medal was awarded. */ @Entity @@ -34,9 +33,6 @@ class PupilMedal( @JoinColumn(name = "medal_id", nullable = false) val medal: Medal, - @Column - val awardedReason: String?, - @Column(nullable = false) val awardedAt: Instant = Instant.now() ) diff --git a/src/main/resources/db/migration/V17__create_medals_tables.sql b/src/main/resources/db/migration/V17__create_medals_tables.sql index 05f8cd2a..ba90fb38 100644 --- a/src/main/resources/db/migration/V17__create_medals_tables.sql +++ b/src/main/resources/db/migration/V17__create_medals_tables.sql @@ -16,7 +16,6 @@ CREATE TABLE pupil_medals ( pupil_user_id BIGINT NOT NULL, classroom_id BIGINT NOT NULL, medal_id BIGINT NOT NULL, - awarded_reason VARCHAR(255), awarded_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), CONSTRAINT pk_pupil_medals PRIMARY KEY (id), CONSTRAINT uk_pupil_medals_pupil_classroom_medal UNIQUE (pupil_user_id, classroom_id, medal_id),