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 a7611edd..0335fc93 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 @@ -62,6 +62,7 @@ class DevDataBootstrap( private val mapStopBootstrap: MapStopBootstrap, private val medalBootstrap: MedalBootstrap, private val taskBootstrap: TaskBootstrap, + private val xpBootstrap: XpBootstrap, private val pupilProgressSeedingService: PupilProgressSeedingService, private val pupilStopProgressRepository: PupilStopProgressRepository, ) : ApplicationRunner { @@ -172,6 +173,12 @@ class DevDataBootstrap( mapStopBootstrap.seedAllMapStops() medalBootstrap.seedAllMedals() + xpBootstrap.seedAllXpEvents() + xpBootstrap.seedPupilXpEvent(pupilAda) + xpBootstrap.seedPupilXpEvent(pupilAda) + xpBootstrap.seedPupilXpEvent(pupilAda) + xpBootstrap.seedPupilXpEvent(pupilAda) + xpBootstrap.seedPupilXpEvent(pupilAda) val activeStops = taskBootstrap.seedAllTasks(classroom = sampleClassroom, teacher = teacher) seedNotebookEntries( classroom = sampleClassroom, 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 index 20d2acbb..a3487b20 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MedalBootstrap.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/MedalBootstrap.kt @@ -1,9 +1,9 @@ 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 edu.ntnu.idi.idatt.backend.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.medals.domain.MedalType +import edu.ntnu.idi.idatt.backend.medals.repository.MedalRepository import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.stereotype.Component diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/XpBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/XpBootstrap.kt new file mode 100644 index 00000000..319904d9 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/XpBootstrap.kt @@ -0,0 +1,86 @@ +package edu.ntnu.idi.idatt.backend.bootstrap + +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEvent +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEventId +import edu.ntnu.idi.idatt.backend.xp.domain.XpEvent +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode +import edu.ntnu.idi.idatt.backend.xp.infrastructure.PupilXpEventRepository +import edu.ntnu.idi.idatt.backend.xp.infrastructure.XpEventRepository +import edu.ntnu.idi.idatt.backend.iam.domain.User +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty +import org.springframework.stereotype.Component + +@Component +@ConditionalOnProperty(name = ["app.bootstrap.enabled"], havingValue = "true") +class XpBootstrap( + private val xpEventRepository: XpEventRepository, + private val pupilXpEventRepository: PupilXpEventRepository, +) { + fun seedAllXpEvents() { + if (xpEventRepository.findByCode(XpEventCode.STOP_COMPLETED) != null) { + return + } + + xpEventRepository.save( + XpEvent( + code = XpEventCode.STOP_COMPLETED, + title = "Stopp fullfort", + xpScore = 75, + repeatable = true, + ), + ) + + xpEventRepository.save( + XpEvent( + code = XpEventCode.MEDAL_AWARDED, + title = "Medalje låst opp", + xpScore = 75, + repeatable = true, + ), + ) + + xpEventRepository.save( + XpEvent( + code = XpEventCode.NOTEBOOK_ENTRY_CREATED, + title = "La inn notat", + xpScore = 10, + repeatable = true, + ), + ) + + xpEventRepository.save( + XpEvent( + code = XpEventCode.UPDATE_AVATAR, + title = "Oppdatert avatar for første gang", + xpScore = 25, + repeatable = false, + ), + ) + } + + fun seedPupilXpEvent(pupil: User) { + val pupilId = requireNotNull(pupil.id) { "Seeded pupil must have an id" } + val xpEvent = xpEventRepository.findByCode(XpEventCode.STOP_COMPLETED) + ?: throw IllegalStateException("XP event ${XpEventCode.STOP_COMPLETED} must be seeded before pupil XP rows") + val xpEventId = requireNotNull(xpEvent.id) { "Seeded XP event must have an id" } + + val existingPupilXpEvent = pupilXpEventRepository.findByIdPupilUserIdAndIdXpEventId(pupilId, xpEventId) + if (existingPupilXpEvent != null) { + existingPupilXpEvent.completionCount += 1 + pupilXpEventRepository.save(existingPupilXpEvent) + return + } + + pupilXpEventRepository.save( + PupilXpEvent( + id = PupilXpEventId( + pupilUserId = pupilId, + xpEventId = xpEventId, + ), + pupil = pupil, + xpEvent = xpEvent, + completionCount = 1, + ), + ) + } +} 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 index 9fc5a1ee..83e16c37 100644 --- 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 @@ -99,7 +99,7 @@ class PupilStopProgressController( ): StopProgressResponse { currentUserResolver.requirePupil(currentUser.subject) return progressService - .updateProgress(pupilUserId, classroomId, stopId, request.toCommand()) + .updateProgress(currentUser, classroomId, stopId, request.toCommand()) .toStopProgressResponse() } } 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 f2680a41..fd98c294 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 @@ -5,6 +5,10 @@ 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.MapStopsRepository import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgressRepository +import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import edu.ntnu.idi.idatt.backend.xp.application.XpService +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent @@ -21,15 +25,16 @@ import java.time.Instant * * @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 + * @property currentUserResolver resolver for the authenticated pupil user + * @property domainEventPublisher publisher for stop progression domain events */ @Service class PupilStopProgressService( private val progressRepository: PupilStopProgressRepository, private val mapStopRepository: MapStopsRepository, + private val currentUserResolver: CurrentUserResolver, private val domainEventPublisher: DomainEventPublisher, + private val xpService: XpService, ) { /** * Returns all stop progress records for a pupil in a classroom. @@ -68,7 +73,7 @@ class PupilStopProgressService( * is higher. If the stop is transitioned to [StopProgressStatus.COMPLETED], the next active * stop is automatically unlocked by transitioning it to [StopProgressStatus.NOT_STARTED]. * - * @param pupilUserId pupil whose progress to update + * @param currentUser authenticated 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 containing the fields to mutate @@ -79,11 +84,13 @@ class PupilStopProgressService( */ @Transactional fun updateProgress( - pupilUserId: Long, + currentUser: CurrentUser, classroomId: Long, stopId: Long, command: UpdateStopProgressCommand, ): PupilStopProgress { + val pupil = currentUserResolver.requirePupil(currentUser.subject) + val pupilUserId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" } val progress = getProgressForStop(pupilUserId, classroomId, stopId) val activeStops = mapStopRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc() @@ -102,6 +109,7 @@ class PupilStopProgressService( progress.completedAt = Instant.now() unlockNextStop(pupilUserId, classroomId, stopId, activeStops) publishCompletionEvents(pupilUserId, classroomId, stopId, progress) + xpService.awardXpEvent(currentUser, XpEventCode.STOP_COMPLETED) } } if (progress.status != StopProgressStatus.COMPLETED) { diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskController.kt index 9be6c621..839eee13 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskController.kt @@ -60,7 +60,7 @@ class TaskController( @RequestBody @Valid request: SubmitStopAnswersRequest, @AuthenticationPrincipal currentUser: CurrentUser, ): StopSubmissionResponse = - taskService.submitStopAnswers(request.toCommand(classroomId, currentUser.subject)).toResponse() + taskService.submitStopAnswers(request.toCommand(classroomId, currentUser)).toResponse() /** * Creates a new draft task owned by the classroom's teacher. diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskRequests.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskRequests.kt index 3479fcce..1ad78b64 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskRequests.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskRequests.kt @@ -218,9 +218,9 @@ private fun LocalizedOptionalTextRequest.toLocalizedOptionalText(): LocalizedOpt fun SubmitStopAnswersRequest.toCommand( classroomId: Long, - authenticatedSubject: String, + currentUser: CurrentUser, ) = edu.ntnu.idi.idatt.backend.game.tasks.application.SubmitStopAnswersCommand( - authenticatedSubject = authenticatedSubject, + currentUser = currentUser, classroomId = classroomId, stopId = stopId, taskAnswers = taskAnswers.map { taskAnswer -> diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskModels.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskModels.kt index f4909c43..69a41e2d 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskModels.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskModels.kt @@ -2,6 +2,7 @@ package edu.ntnu.idi.idatt.backend.game.tasks.application import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskPassingRule import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskType +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import java.time.Instant /** @@ -147,7 +148,7 @@ data class TaskSummary( * Command used to submit answers for all tasks at a given stop. */ data class SubmitStopAnswersCommand( - val authenticatedSubject: String, + val currentUser: CurrentUser, val classroomId: Long, val stopId: Long, val taskAnswers: List, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskService.kt index 5685252d..59b50880 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/application/TaskService.kt @@ -232,7 +232,7 @@ class TaskService( */ @Transactional fun submitStopAnswers(command: SubmitStopAnswersCommand): StopSubmissionResult { - val (_, user) = requireParticipatingClassroom(command.authenticatedSubject, command.classroomId) + val (_, user) = requireParticipatingClassroom(command.currentUser.subject, command.classroomId) if (user.role != UserRole.PUPIL) { throw ResponseStatusException(HttpStatus.FORBIDDEN, "Only pupils may submit stop answers") } @@ -271,7 +271,7 @@ class TaskService( val totalMaxScore = tasks.sumOf { it.maxScore } val passed = taskResults.all { it.passed } val updatedProgress = updateProgressAfterSubmission( - pupilId = pupilId, + currentUser = command.currentUser, classroomId = command.classroomId, stopId = command.stopId, currentStatus = progress.status, @@ -577,7 +577,7 @@ class TaskService( } private fun updateProgressAfterSubmission( - pupilId: Long, + currentUser: CurrentUser, classroomId: Long, stopId: Long, currentStatus: StopProgressStatus, @@ -588,7 +588,7 @@ class TaskService( when { passed && currentStatus == StopProgressStatus.NOT_STARTED -> { pupilStopProgressService.updateProgress( - pupilId, + currentUser, classroomId, stopId, UpdateStopProgressCommand( @@ -599,7 +599,7 @@ class TaskService( ), ) pupilStopProgressService.updateProgress( - pupilId, + currentUser, classroomId, stopId, UpdateStopProgressCommand( @@ -612,7 +612,7 @@ class TaskService( } passed && currentStatus == StopProgressStatus.IN_PROGRESS -> pupilStopProgressService.updateProgress( - pupilId, + currentUser, classroomId, stopId, UpdateStopProgressCommand( @@ -624,7 +624,7 @@ class TaskService( ) passed -> pupilStopProgressService.updateProgress( - pupilId, + currentUser, classroomId, stopId, UpdateStopProgressCommand( @@ -636,7 +636,7 @@ class TaskService( ) currentStatus == StopProgressStatus.NOT_STARTED -> pupilStopProgressService.updateProgress( - pupilId, + currentUser, classroomId, stopId, UpdateStopProgressCommand( @@ -648,7 +648,7 @@ class TaskService( ) else -> pupilStopProgressService.updateProgress( - pupilId, + currentUser, classroomId, stopId, UpdateStopProgressCommand( 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/medals/api/MedalsController.kt similarity index 91% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/api/MedalsController.kt index 64ba75a5..95279608 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/api/MedalsController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/api/MedalsController.kt @@ -1,8 +1,8 @@ -package edu.ntnu.idi.idatt.backend.game.medals.api +package edu.ntnu.idi.idatt.backend.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.medals.application.MedalService +import edu.ntnu.idi.idatt.backend.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.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 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/medals/application/MedalService.kt similarity index 79% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/application/MedalService.kt index b053efac..04c534a1 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/application/MedalService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/application/MedalService.kt @@ -1,11 +1,14 @@ -package edu.ntnu.idi.idatt.backend.game.medals.application +package edu.ntnu.idi.idatt.backend.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.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.medals.domain.PupilMedal +import edu.ntnu.idi.idatt.backend.medals.repository.MedalRepository +import edu.ntnu.idi.idatt.backend.medals.repository.PupilMedalRepository import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.xp.application.XpService +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service import org.springframework.transaction.PlatformTransactionManager @@ -24,6 +27,7 @@ import java.util.stream.Collectors class MedalService( private val medalRepository: MedalRepository, private val pupilMedalRepository: PupilMedalRepository, + private val xpService: XpService, transactionManager: PlatformTransactionManager, ) { private val awardTransaction = TransactionTemplate(transactionManager).apply { @@ -80,7 +84,16 @@ class MedalService( pupil = pupil, classroom = classroom, medal = medal, - ) + ), + ) + xpService.awardXpEvent( + CurrentUser( + subject = pupilId.toString(), + portalType = "pupil", + email = null, + authorities = setOf("ROLE_PUPIL"), + ), + XpEventCode.MEDAL_AWARDED, ) } } catch (exception: DataIntegrityViolationException) { 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/medals/domain/Medal.kt similarity index 95% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/Medal.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/domain/Medal.kt index 280cd12d..4699d7e6 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/Medal.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/domain/Medal.kt @@ -1,4 +1,4 @@ -package edu.ntnu.idi.idatt.backend.game.medals.domain +package edu.ntnu.idi.idatt.backend.medals.domain import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop import jakarta.persistence.* 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/medals/domain/MedalType.kt similarity index 55% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/MedalType.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/domain/MedalType.kt index 8388aeb8..645c9dde 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/MedalType.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/domain/MedalType.kt @@ -1,4 +1,4 @@ -package edu.ntnu.idi.idatt.backend.game.medals.domain +package edu.ntnu.idi.idatt.backend.medals.domain enum class MedalType { STOP_COMPLETION, 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/medals/domain/PupilMedal.kt similarity index 95% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/domain/PupilMedal.kt index 81452755..90d1bb81 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/domain/PupilMedal.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/domain/PupilMedal.kt @@ -1,4 +1,4 @@ -package edu.ntnu.idi.idatt.backend.game.medals.domain +package edu.ntnu.idi.idatt.backend.medals.domain import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom 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/medals/repository/MedalRepository.kt similarity index 73% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/repository/MedalRepository.kt index 5aa67708..de1ee167 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/MedalRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/repository/MedalRepository.kt @@ -1,6 +1,6 @@ -package edu.ntnu.idi.idatt.backend.game.medals.repository +package edu.ntnu.idi.idatt.backend.medals.repository -import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.medals.domain.Medal import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository 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/medals/repository/PupilMedalRepository.kt similarity index 79% rename from src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt rename to src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/repository/PupilMedalRepository.kt index 1ca0d753..965335f3 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/medals/repository/PupilMedalRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/medals/repository/PupilMedalRepository.kt @@ -1,6 +1,6 @@ -package edu.ntnu.idi.idatt.backend.game.medals.repository +package edu.ntnu.idi.idatt.backend.medals.repository -import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal +import edu.ntnu.idi.idatt.backend.medals.domain.PupilMedal import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import java.util.stream.Stream diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt index 1e5a65e5..6c53dc07 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt @@ -7,6 +7,8 @@ import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookEntry import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType import edu.ntnu.idi.idatt.backend.notebook.infrastructure.NotebookEntryRepository +import edu.ntnu.idi.idatt.backend.xp.application.XpService +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -25,6 +27,7 @@ class NotebookService( private val currentUserResolver: CurrentUserResolver, private val mapStopsRepository: MapStopsRepository, private val pupilGameProgressRepository: PupilGameProgressRepository, + private val xpService: XpService, ) { /** * Returns all notebook entries owned by the authenticated pupil. @@ -55,6 +58,7 @@ class NotebookService( @Transactional fun createNotebookEntry(command: CreateNotebookEntryCommand): NotebookEntry { val pupil = currentUserResolver.requirePupil(command.currentUser.subject) + val pupilId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" } val classroom = currentUserResolver.getClassroomByUser(command.currentUser) if (command.sourceType == NotebookSourceType.GAME) { @@ -70,6 +74,8 @@ class NotebookService( ResponseStatusException(HttpStatus.NOT_FOUND, "Map stop not found") } + xpService.awardXpEvent(command.currentUser, XpEventCode.NOTEBOOK_ENTRY_CREATED) + val notebookEntry = NotebookEntry( pupil = if (command.sourceType == NotebookSourceType.PUPIL) pupil else null, classroom = classroom, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/application/UserAvatarService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/application/UserAvatarService.kt index 3259c32b..cbeb19d5 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/application/UserAvatarService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/application/UserAvatarService.kt @@ -2,8 +2,11 @@ package edu.ntnu.idi.idatt.backend.users.avatar.application 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.security.CurrentUser import edu.ntnu.idi.idatt.backend.users.avatar.domain.UserAvatar import edu.ntnu.idi.idatt.backend.users.avatar.infrastructure.UserAvatarRepository +import edu.ntnu.idi.idatt.backend.xp.application.XpService +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -19,6 +22,7 @@ import org.springframework.web.server.ResponseStatusException class UserAvatarService( private val currentUserResolver: CurrentUserResolver, private val userAvatarRepository: UserAvatarRepository, + private val xpService: XpService, ) { /** * Returns the current authenticated pupil's avatar. @@ -51,11 +55,23 @@ class UserAvatarService( ): UserAvatar { val user = currentUserResolver.requirePupil(authenticatedSubject) val userAvatar = findUserAvatar(user) + userAvatar.update( bodyType = command.bodyType, skinTone = command.skinTone, outfitStyle = command.outfitStyle, ) + + xpService.awardXpEvent( + CurrentUser( + subject = authenticatedSubject, + portalType = "pupil", + email = null, + authorities = setOf("ROLE_PUPIL"), + ), + XpEventCode.UPDATE_AVATAR, + ) + return userAvatarRepository.save(userAvatar) } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/application/XpService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/application/XpService.kt new file mode 100644 index 00000000..be545d8d --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/application/XpService.kt @@ -0,0 +1,136 @@ +package edu.ntnu.idi.idatt.backend.xp.application + +import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEvent +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEventId +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode +import edu.ntnu.idi.idatt.backend.xp.infrastructure.PupilXpEventRepository +import edu.ntnu.idi.idatt.backend.xp.infrastructure.XpEventRepository +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.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import org.springframework.web.server.ResponseStatusException +import java.time.Instant + +/** + * Application service for awarding XP events to pupils. + * + * The service resolves the authenticated pupil, loads the configured XP event + * by its stable [XpEventCode], and either creates or updates the pupil's + * progress row depending on whether the event is repeatable. + * + * @property pupilXpEventRepository repository for awarded pupil XP rows + * @property xpEventRepository repository for XP event definitions + * @property pupilGameProgressRepository repository for classroom-scoped pupil game progress + * @property currentUserResolver resolver for the authenticated pupil user + */ +@Service +class XpService( + private val pupilXpEventRepository: PupilXpEventRepository, + private val xpEventRepository: XpEventRepository, + private val pupilGameProgressRepository: PupilGameProgressRepository, + private val currentUserResolver: CurrentUserResolver, +) { + companion object { + private const val XP_PER_LEVEL = 150 + } + + /** + * Awards one XP event to the authenticated pupil. + * + * For non-repeatable events, duplicate awards are ignored. For repeatable + * events, the stored completion count is incremented on the existing + * pupil-event row. + * + * @param currentUser authenticated pupil receiving the award + * @param eventCode stable code for the XP event to award + * @throws ResponseStatusException when the XP event definition does not exist + */ + @Transactional + fun awardXpEvent(currentUser: CurrentUser, eventCode: XpEventCode) { + val pupil = currentUserResolver.requirePupil(currentUser.subject) + val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" } + + val xpEvent = xpEventRepository.findByCode(eventCode) ?: return + val xpEventId = requireNotNull(xpEvent.id) { "XP event is missing an id" } + + val pupilXpEvent = pupilXpEventRepository.findByIdPupilUserIdAndIdXpEventId(pupilId, xpEventId) + + if (pupilXpEvent != null) { + if (!xpEvent.repeatable) return + + pupilXpEvent.completionCount += 1 + pupilXpEventRepository.save(pupilXpEvent) + } else { + pupilXpEventRepository.save( + PupilXpEvent( + id = PupilXpEventId(pupilUserId = pupilId, xpEventId = xpEventId), + pupil = pupil, + xpEvent = xpEvent, + ), + ) + } + updatePupilGameProgressLevel(currentUser) + } + + /** + * Recomputes the authenticated pupil's classroom-scoped XP total from awarded XP events. + * + * The method sums the configured XP score for each awarded event multiplied + * by its completion count, derives the matching level from the total XP, + * then stores the updated progression snapshot on the pupil's aggregated + * classroom progress record. + * + * @param currentUser authenticated pupil whose progress should be recalculated + * @throws ResponseStatusException when no game progress row exists for the active classroom + */ + @Transactional + fun updatePupilGameProgressLevel(currentUser: CurrentUser) { + val pupil = currentUserResolver.requirePupil(currentUser.subject) + val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" } + + val classroom = try { + currentUserResolver.getClassroomByUser(currentUser) + } catch (_: ResponseStatusException) { + return + } + val classroomId = requireNotNull(classroom.id) { "Classroom is missing an id" } + + val pupilGameProgress = pupilGameProgressRepository.findByPupilIdAndClassroomId(pupilId, classroomId) + ?: return + + val pupilXpEvents = pupilXpEventRepository.findAllByIdPupilUserId(pupilId) + val totalXp = pupilXpEvents.sumOf { pupilXpEvent -> + val xpEvent = requireNotNull(pupilXpEvent.xpEvent) { + "Pupil XP event is missing its XP event reference" + } + xpEvent.xpScore * pupilXpEvent.completionCount + } + val currentLevel = calculateLevelFromXp(totalXp) + + pupilGameProgress.updateProgress( + totalScore = totalXp, + totalXp = totalXp, + currentLevel = currentLevel, + completedStopsCount = pupilGameProgress.completedStopsCount, + completedTasksCount = pupilGameProgress.completedTasksCount, + finalBossCompleted = pupilGameProgress.finalBossCompleted, + lastActivityAt = Instant.now(), + ) + pupilGameProgressRepository.save(pupilGameProgress) + } + + /** + * Maps accumulated XP to a 1-based level. + * + * Each full [XP_PER_LEVEL] XP increases the pupil's level by one, while + * pupils with no XP remain at level 1. + * + * @param totalXp classroom-scoped accumulated XP. + * @return derived 1-based level. + */ + private fun calculateLevelFromXp(totalXp: Int): Int = + (totalXp / XP_PER_LEVEL) + 1 +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/PupilXpEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/PupilXpEvent.kt new file mode 100644 index 00000000..e9b4fde8 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/PupilXpEvent.kt @@ -0,0 +1,40 @@ +package edu.ntnu.idi.idatt.backend.xp.domain + +import edu.ntnu.idi.idatt.backend.iam.domain.User +import jakarta.persistence.Column +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 + +/** + * Records that a pupil has received a specific XP event. + * + * This join entity keeps one row per pupil and XP event by using a composite + * key over the pupil and event identifiers. For repeatable events, the same + * row tracks how many times the pupil has completed the event. + * + * @property id composite identifier for the awarded event + * @property pupil pupil who received the event + * @property xpEvent XP event definition that was awarded + * @property completionCount number of times the pupil has completed the event + */ +@Entity +@Table(name = "pupil_xp_events") +class PupilXpEvent( + @EmbeddedId + var id: PupilXpEventId = PupilXpEventId(), + @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("xpEventId") + @JoinColumn(name = "xp_event_id", nullable = false) + var xpEvent: XpEvent? = null, + @Column(name = "completion_count", nullable = false) + var completionCount: Int = 1, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/PupilXpEventId.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/PupilXpEventId.kt new file mode 100644 index 00000000..58547f0d --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/PupilXpEventId.kt @@ -0,0 +1,22 @@ +package edu.ntnu.idi.idatt.backend.xp.domain + +import jakarta.persistence.Column +import jakarta.persistence.Embeddable +import java.io.Serializable + +/** + * Composite identifier for [PupilXpEvent]. + * + * The identifier is made from the pupil user id and the XP event id so one + * row can represent one pupil-event pair. + * + * @property pupilUserId identifier of the awarded pupil + * @property xpEventId identifier of the awarded XP event definition + */ +@Embeddable +data class PupilXpEventId( + @Column(name = "pupil_user_id") + var pupilUserId: Long = 0, + @Column(name = "xp_event_id") + var xpEventId: Long = 0, +) : Serializable diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/XpEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/XpEvent.kt new file mode 100644 index 00000000..19c6d905 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/XpEvent.kt @@ -0,0 +1,40 @@ +package edu.ntnu.idi.idatt.backend.xp.domain + +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.EnumType +import jakarta.persistence.Enumerated +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.Table + +/** + * Defines an XP-awarding event that can be linked to a pupil. + * + * The entity represents the catalog entry for a single awardable XP source, + * such as completing a task or reaching a milestone. Actual pupil awards are + * tracked separately through [PupilXpEvent]. + * + * @property id database identifier + * @property code stable business key used to identify the event in code + * @property title human-readable label for the event + * @property xpScore amount of XP granted when the event is awarded + * @property repeatable whether the same pupil may be awarded the event more than once + */ +@Entity +@Table(name = "xp_events") +class XpEvent( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long? = null, + @Enumerated(EnumType.STRING) + @Column(name = "code", nullable = false, unique = true, length = 100) + var code: XpEventCode, + @Column(name = "title", nullable = false) + var title: String = "", + @Column(name = "xp_score", nullable = false) + var xpScore: Int = 0, + @Column(name = "repeatable", nullable = false) + var repeatable: Boolean = false, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/XpEventCode.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/XpEventCode.kt new file mode 100644 index 00000000..45211d74 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/domain/XpEventCode.kt @@ -0,0 +1,15 @@ +package edu.ntnu.idi.idatt.backend.xp.domain + +/** + * Stable identifiers for XP event definitions. + * + * The enum is used as the canonical business key for XP awards, while the + * corresponding [XpEvent] rows still hold presentation fields such as title + * and score in the database. + */ +enum class XpEventCode { + STOP_COMPLETED, + MEDAL_AWARDED, + NOTEBOOK_ENTRY_CREATED, + UPDATE_AVATAR, +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/infrastructure/PupilXpEventRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/infrastructure/PupilXpEventRepository.kt new file mode 100644 index 00000000..b34c04de --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/infrastructure/PupilXpEventRepository.kt @@ -0,0 +1,38 @@ +package edu.ntnu.idi.idatt.backend.xp.infrastructure + +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEventId +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEvent +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +/** + * Repository for awarded XP events linked to pupils. + */ +@Repository +interface PupilXpEventRepository : JpaRepository { + /** + * Returns all awarded XP event rows for one pupil. + * + * @param pupilUserId identifier of the pupil. + * @return awarded XP event links for the given pupil. + */ + fun findAllByIdPupilUserId(pupilUserId: Long): List + + /** + * Checks whether one XP event has already been awarded to one pupil. + * + * @param pupilUserId identifier of the pupil. + * @param xpEventId identifier of the XP event definition. + * @return `true` when the composite award row already exists. + */ + fun existsByIdPupilUserIdAndIdXpEventId(pupilUserId: Long, xpEventId: Long): Boolean + + /** + * Finds the awarded XP row for one pupil-event pair. + * + * @param pupilUserId identifier of the pupil. + * @param xpEventId identifier of the XP event definition. + * @return awarded XP row, or `null` when absent. + */ + fun findByIdPupilUserIdAndIdXpEventId(pupilUserId: Long, xpEventId: Long): PupilXpEvent? +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/infrastructure/XpEventRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/infrastructure/XpEventRepository.kt new file mode 100644 index 00000000..31eb1752 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/xp/infrastructure/XpEventRepository.kt @@ -0,0 +1,20 @@ +package edu.ntnu.idi.idatt.backend.xp.infrastructure + +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode +import edu.ntnu.idi.idatt.backend.xp.domain.XpEvent +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +/** + * Repository for persisted [XpEvent] definitions. + */ +@Repository +interface XpEventRepository : JpaRepository { + /** + * Finds one XP event definition by its stable business code. + * + * @param code canonical XP event identifier. + * @return matching event definition, or `null` when absent. + */ + fun findByCode(code: XpEventCode): XpEvent? +} diff --git a/src/main/resources/db/migration/V21__create_xp_tables.sql b/src/main/resources/db/migration/V21__create_xp_tables.sql new file mode 100644 index 00000000..10a02809 --- /dev/null +++ b/src/main/resources/db/migration/V21__create_xp_tables.sql @@ -0,0 +1,22 @@ +CREATE TABLE xp_events ( + id BIGINT NOT NULL AUTO_INCREMENT, + code VARCHAR(100) NOT NULL, + title VARCHAR(255) NOT NULL, + xp_score INT NOT NULL, + repeatable BOOLEAN NOT NULL DEFAULT FALSE, + CONSTRAINT pk_xp_events PRIMARY KEY (id), + CONSTRAINT uk_xp_events_code UNIQUE (code) +); + +CREATE TABLE pupil_xp_events ( + pupil_user_id BIGINT NOT NULL, + xp_event_id BIGINT NOT NULL, + completion_count INT NOT NULL DEFAULT 1, + CONSTRAINT pk_pupil_xp_events PRIMARY KEY (pupil_user_id, xp_event_id), + CONSTRAINT fk_pupil_xp_events_pupil + FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_pupil_xp_events_xp_event + FOREIGN KEY (xp_event_id) REFERENCES xp_events (id) ON DELETE CASCADE +); + +CREATE INDEX idx_pupil_xp_events_xp_event ON pupil_xp_events (xp_event_id); 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 dc4fd5e3..e0da7563 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,7 +1,6 @@ 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 @@ -10,9 +9,12 @@ 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.xp.application.XpService +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.security.CurrentUser import edu.ntnu.idi.idatt.backend.shared.events.DomainEvent import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent @@ -29,7 +31,6 @@ 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 { @@ -101,7 +102,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = StopProgressStatus.NOT_STARTED, null, null, null), ) @@ -120,7 +122,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = StopProgressStatus.IN_PROGRESS, null, null, null), ) @@ -139,7 +142,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), ) @@ -160,7 +164,8 @@ class PupilStopProgressServiceTests { // first completion service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), ) val firstCompletedAt = record.completedAt @@ -182,7 +187,8 @@ class PupilStopProgressServiceTests { val exception = assertThrows { service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = StopProgressStatus.IN_PROGRESS, null, null, null), ) } @@ -203,7 +209,8 @@ class PupilStopProgressServiceTests { val exception = assertThrows { service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), ) } @@ -222,7 +229,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = 80, medalAwarded = null), ) @@ -239,7 +247,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = 50, medalAwarded = null), ) @@ -256,7 +265,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = null, currentTaskId = 7L, bestScore = null, medalAwarded = null), ) @@ -276,7 +286,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand( status = StopProgressStatus.COMPLETED, currentTaskId = 99L, @@ -298,7 +309,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = null, medalAwarded = true), ) @@ -316,7 +328,8 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, classroomId = 2L, stopId = 1L, + currentUser = pupilCurrentUser(), + classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = null, currentTaskId = null, bestScore = null, medalAwarded = null), ) @@ -337,7 +350,7 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) service.updateProgress( - pupilUserId = 1L, + currentUser = pupilCurrentUser(), classroomId = 2L, stopId = 99L, command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), @@ -360,7 +373,7 @@ class PupilStopProgressServiceTests { stubFindAndSave(progressRepository, record) val result = service.updateProgress( - pupilUserId = 1L, + currentUser = pupilCurrentUser(), classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), @@ -563,8 +576,29 @@ class PupilStopProgressServiceTests { progressRepository: PupilStopProgressRepository, mapStopRepository: MapStopsRepository, domainEventPublisher: DomainEventPublisher = Mockito.mock(DomainEventPublisher::class.java), + currentUserResolver: CurrentUserResolver = Mockito.mock(CurrentUserResolver::class.java).also { + Mockito.`when`(it.requirePupil("1")).thenReturn(pupil()) + }, + xpService: XpService = Mockito.mock(XpService::class.java), ): PupilStopProgressService = - PupilStopProgressService(progressRepository, mapStopRepository, domainEventPublisher) + PupilStopProgressService(progressRepository, mapStopRepository, currentUserResolver, domainEventPublisher, xpService) + + private fun pupilCurrentUser(): CurrentUser = + CurrentUser( + subject = "1", + portalType = "pupil", + email = null, + authorities = setOf("ROLE_PUPIL"), + ) + + private fun pupil(): User = + User( + id = 1L, + username = "pupil-one", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) private fun stubFind(repo: PupilStopProgressRepository, record: PupilStopProgress) { Mockito.`when`(repo.findByIdPupilUserIdAndIdClassroomIdAndIdStopId( diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/medals/MedalServiceTests.kt similarity index 83% rename from src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt rename to src/test/kotlin/edu/ntnu/idi/idatt/backend/medals/MedalServiceTests.kt index dc0ec094..18824559 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/medals/MedalServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/medals/MedalServiceTests.kt @@ -1,12 +1,13 @@ -package edu.ntnu.idi.idatt.backend.game.medals +package edu.ntnu.idi.idatt.backend.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.medals.application.MedalService +import edu.ntnu.idi.idatt.backend.medals.domain.Medal +import edu.ntnu.idi.idatt.backend.medals.domain.MedalType +import edu.ntnu.idi.idatt.backend.medals.domain.PupilMedal +import edu.ntnu.idi.idatt.backend.medals.repository.MedalRepository +import edu.ntnu.idi.idatt.backend.medals.repository.PupilMedalRepository +import edu.ntnu.idi.idatt.backend.xp.application.XpService 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 @@ -25,7 +26,8 @@ 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, transactionManager()) + val xpService = Mockito.mock(XpService::class.java) + val service = MedalService(medalRepository, pupilMedalRepository, xpService, transactionManager()) Mockito.`when`(medalRepository.findByStopId(5L)).thenReturn(medal(stopId = 5L)) Mockito.`when`(pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(1L, 2L, 10L)) @@ -44,7 +46,8 @@ class MedalServiceTests { 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 xpService = Mockito.mock(XpService::class.java) + val service = MedalService(medalRepository, pupilMedalRepository, xpService, transactionManager()) val exception = DataIntegrityViolationException("foreign key failure") Mockito.`when`(medalRepository.findByStopId(5L)).thenReturn(medal(stopId = 5L)) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt index 099de886..215e3c24 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt @@ -4,6 +4,7 @@ import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.xp.application.XpService 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 @@ -33,11 +34,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -60,11 +63,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -105,11 +110,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -139,11 +146,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -173,11 +182,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -208,11 +219,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -244,11 +257,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -276,11 +291,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) @@ -304,11 +321,13 @@ class NotebookServiceTests { val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val xpService = Mockito.mock(XpService::class.java) val service = NotebookService( notebookEntryRepository, currentUserResolver, mapStopsRepository, pupilGameProgressRepository, + xpService, ) val currentUser = currentUser("42") val pupil = pupilUser(42L) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/UserAvatarServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/UserAvatarServiceTests.kt index 05b6fe12..68a2a4b3 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/UserAvatarServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/users/avatar/UserAvatarServiceTests.kt @@ -4,6 +4,7 @@ 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.xp.application.XpService import edu.ntnu.idi.idatt.backend.users.avatar.application.UserAvatarService import edu.ntnu.idi.idatt.backend.users.avatar.domain.UserAvatar import edu.ntnu.idi.idatt.backend.users.avatar.infrastructure.UserAvatarRepository @@ -20,7 +21,8 @@ class UserAvatarServiceTests { fun `get user avatar returns persisted avatar for authenticated pupil`() { val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) val userAvatarRepository = Mockito.mock(UserAvatarRepository::class.java) - val service = UserAvatarService(currentUserResolver, userAvatarRepository) + val xpService = Mockito.mock(XpService::class.java) + val service = UserAvatarService(currentUserResolver, userAvatarRepository, xpService) val user = pupilUser(42L) val avatar = UserAvatar( user = user, @@ -43,7 +45,8 @@ class UserAvatarServiceTests { fun `get user avatar rejects malformed authenticated subject`() { val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) val userAvatarRepository = Mockito.mock(UserAvatarRepository::class.java) - val service = UserAvatarService(currentUserResolver, userAvatarRepository) + val xpService = Mockito.mock(XpService::class.java) + val service = UserAvatarService(currentUserResolver, userAvatarRepository, xpService) val exception = ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid authenticated user subject") Mockito.`when`(currentUserResolver.requirePupil("not-a-number")).thenThrow(exception) @@ -59,7 +62,8 @@ class UserAvatarServiceTests { fun `get user avatar rejects unknown authenticated user`() { val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) val userAvatarRepository = Mockito.mock(UserAvatarRepository::class.java) - val service = UserAvatarService(currentUserResolver, userAvatarRepository) + val xpService = Mockito.mock(XpService::class.java) + val service = UserAvatarService(currentUserResolver, userAvatarRepository, xpService) val exception = ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authenticated user was not found") Mockito.`when`(currentUserResolver.requirePupil("42")).thenThrow(exception) @@ -75,7 +79,8 @@ class UserAvatarServiceTests { fun `get user avatar rejects teacher user`() { val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) val userAvatarRepository = Mockito.mock(UserAvatarRepository::class.java) - val service = UserAvatarService(currentUserResolver, userAvatarRepository) + val xpService = Mockito.mock(XpService::class.java) + val service = UserAvatarService(currentUserResolver, userAvatarRepository, xpService) val exception = ResponseStatusException(HttpStatus.FORBIDDEN, "Only pupils are allowed") Mockito.`when`(currentUserResolver.requirePupil("7")).thenThrow(exception) @@ -91,7 +96,8 @@ class UserAvatarServiceTests { fun `get user avatar rejects pupil without avatar row`() { val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) val userAvatarRepository = Mockito.mock(UserAvatarRepository::class.java) - val service = UserAvatarService(currentUserResolver, userAvatarRepository) + val xpService = Mockito.mock(XpService::class.java) + val service = UserAvatarService(currentUserResolver, userAvatarRepository, xpService) val user = pupilUser(42L) Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(user) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/xp/XpServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/xp/XpServiceTests.kt new file mode 100644 index 00000000..50ccc63b --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/xp/XpServiceTests.kt @@ -0,0 +1,202 @@ +package edu.ntnu.idi.idatt.backend.xp + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +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.xp.application.XpService +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEvent +import edu.ntnu.idi.idatt.backend.xp.domain.PupilXpEventId +import edu.ntnu.idi.idatt.backend.xp.domain.XpEvent +import edu.ntnu.idi.idatt.backend.xp.domain.XpEventCode +import edu.ntnu.idi.idatt.backend.xp.infrastructure.PupilXpEventRepository +import edu.ntnu.idi.idatt.backend.xp.infrastructure.XpEventRepository +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.security.CurrentUser +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Test +import org.mockito.ArgumentCaptor +import org.mockito.Mockito + +class XpServiceTests { + @Test + fun `award xp event creates pupil event row and updates progress for first award`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val pupilXpEventRepository = Mockito.mock(PupilXpEventRepository::class.java) + val xpEventRepository = Mockito.mock(XpEventRepository::class.java) + val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val service = XpService( + pupilXpEventRepository, + xpEventRepository, + pupilGameProgressRepository, + currentUserResolver, + ) + val currentUser = currentUser() + val pupil = pupil() + val classroom = classroom() + val xpEvent = xpEvent(id = 10L, xpScore = 75, repeatable = false) + val progress = gameProgress(pupil, classroom) + + Mockito.`when`(currentUserResolver.requirePupil(currentUser.subject)).thenReturn(pupil) + Mockito.`when`(currentUserResolver.getClassroomByUser(currentUser)).thenReturn(classroom) + Mockito.`when`(xpEventRepository.findByCode(XpEventCode.STOP_COMPLETED)).thenReturn(xpEvent) + Mockito.`when`(pupilXpEventRepository.findByIdPupilUserIdAndIdXpEventId(1L, 10L)).thenReturn(null) + Mockito.`when`(pupilXpEventRepository.findAllByIdPupilUserId(1L)).thenReturn( + listOf( + PupilXpEvent( + id = PupilXpEventId(pupilUserId = 1L, xpEventId = 10L), + pupil = pupil, + xpEvent = xpEvent, + completionCount = 1, + ), + ), + ) + Mockito.`when`(pupilGameProgressRepository.findByPupilIdAndClassroomId(1L, 5L)).thenReturn(progress) + + service.awardXpEvent(currentUser, XpEventCode.STOP_COMPLETED) + + val captor = ArgumentCaptor.forClass(PupilXpEvent::class.java) + Mockito.verify(pupilXpEventRepository).save(captor.capture()) + val savedAward = captor.value + assertEquals(1L, savedAward.id.pupilUserId) + assertEquals(10L, savedAward.id.xpEventId) + assertSame(pupil, savedAward.pupil) + assertSame(xpEvent, savedAward.xpEvent) + assertEquals(1, savedAward.completionCount) + + assertEquals(75, progress.totalXp) + assertEquals(1, progress.currentLevel) + Mockito.verify(pupilGameProgressRepository).save(progress) + } + + @Test + fun `award xp event ignores duplicate non repeatable award`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val pupilXpEventRepository = Mockito.mock(PupilXpEventRepository::class.java) + val xpEventRepository = Mockito.mock(XpEventRepository::class.java) + val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val service = XpService( + pupilXpEventRepository, + xpEventRepository, + pupilGameProgressRepository, + currentUserResolver, + ) + val currentUser = currentUser() + val pupil = pupil() + val existingAward = PupilXpEvent( + id = PupilXpEventId(pupilUserId = 1L, xpEventId = 10L), + pupil = pupil, + xpEvent = xpEvent(id = 10L, xpScore = 75, repeatable = false), + completionCount = 1, + ) + + Mockito.`when`(currentUserResolver.requirePupil(currentUser.subject)).thenReturn(pupil) + Mockito.`when`(xpEventRepository.findByCode(XpEventCode.STOP_COMPLETED)).thenReturn(existingAward.xpEvent) + Mockito.`when`(pupilXpEventRepository.findByIdPupilUserIdAndIdXpEventId(1L, 10L)).thenReturn(existingAward) + + service.awardXpEvent(currentUser, XpEventCode.STOP_COMPLETED) + + Mockito.verify(pupilXpEventRepository, Mockito.never()).save(Mockito.any(PupilXpEvent::class.java)) + Mockito.verifyNoInteractions(pupilGameProgressRepository) + } + + @Test + fun `award xp event increments repeatable award and recalculates level from total xp`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val pupilXpEventRepository = Mockito.mock(PupilXpEventRepository::class.java) + val xpEventRepository = Mockito.mock(XpEventRepository::class.java) + val pupilGameProgressRepository = Mockito.mock(PupilGameProgressRepository::class.java) + val service = XpService( + pupilXpEventRepository, + xpEventRepository, + pupilGameProgressRepository, + currentUserResolver, + ) + val currentUser = currentUser() + val pupil = pupil() + val classroom = classroom() + val xpEvent = xpEvent(id = 10L, xpScore = 80, repeatable = true) + val existingAward = PupilXpEvent( + id = PupilXpEventId(pupilUserId = 1L, xpEventId = 10L), + pupil = pupil, + xpEvent = xpEvent, + completionCount = 1, + ) + val progress = gameProgress( + pupil = pupil, + classroom = classroom, + totalXp = 80, + currentLevel = 1, + ) + + Mockito.`when`(currentUserResolver.requirePupil(currentUser.subject)).thenReturn(pupil) + Mockito.`when`(currentUserResolver.getClassroomByUser(currentUser)).thenReturn(classroom) + Mockito.`when`(xpEventRepository.findByCode(XpEventCode.STOP_COMPLETED)).thenReturn(xpEvent) + Mockito.`when`(pupilXpEventRepository.findByIdPupilUserIdAndIdXpEventId(1L, 10L)).thenReturn(existingAward) + Mockito.`when`(pupilXpEventRepository.findAllByIdPupilUserId(1L)).thenReturn(listOf(existingAward)) + Mockito.`when`(pupilGameProgressRepository.findByPupilIdAndClassroomId(1L, 5L)).thenReturn(progress) + + service.awardXpEvent(currentUser, XpEventCode.STOP_COMPLETED) + + assertEquals(2, existingAward.completionCount) + Mockito.verify(pupilXpEventRepository).save(existingAward) + assertEquals(160, progress.totalXp) + assertEquals(2, progress.currentLevel) + Mockito.verify(pupilGameProgressRepository).save(progress) + } + + private fun currentUser(): CurrentUser = + CurrentUser( + subject = "1", + portalType = "pupil", + email = null, + authorities = setOf("ROLE_PUPIL"), + ) + + private fun pupil(): User = + User( + id = 1L, + username = "ada", + passwordHash = "hash", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + + private fun classroom(): Classroom = + Classroom( + id = 5L, + ownerTeacherId = 9L, + title = "XP Classroom", + ) + + private fun xpEvent(id: Long, xpScore: Int, repeatable: Boolean): XpEvent = + XpEvent( + id = id, + code = XpEventCode.STOP_COMPLETED, + title = "Stop complete", + xpScore = xpScore, + repeatable = repeatable, + ) + + private fun gameProgress( + pupil: User, + classroom: Classroom, + totalXp: Int = 0, + currentLevel: Int = 1, + ): PupilGameProgress = + PupilGameProgress( + id = PupilGameProgressId( + pupilUserId = requireNotNull(pupil.id), + classroomId = classroom.id, + ), + pupil = pupil, + classroom = classroom, + totalScore = 0, + totalXp = totalXp, + currentLevel = currentLevel, + ) +}