From 51da585a73bf2ddd396c68d5d00687e52e0363e8 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:08:31 +0200 Subject: [PATCH 01/16] add migration for new columns --- .../migration/V13__add_task_item_selection_feedback.sql | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 src/main/resources/db/migration/V13__add_task_item_selection_feedback.sql diff --git a/src/main/resources/db/migration/V13__add_task_item_selection_feedback.sql b/src/main/resources/db/migration/V13__add_task_item_selection_feedback.sql new file mode 100644 index 00000000..f7976df6 --- /dev/null +++ b/src/main/resources/db/migration/V13__add_task_item_selection_feedback.sql @@ -0,0 +1,8 @@ +ALTER TABLE task_items + ADD COLUMN is_correct_selection BOOLEAN NOT NULL DEFAULT FALSE; + +ALTER TABLE task_items + ADD COLUMN selection_explanation_text TEXT; + +ALTER TABLE task_item_translations + ADD COLUMN selection_explanation_text TEXT; From 74ddd53913b81381a54121ca2a3a05718de5d832 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:08:58 +0200 Subject: [PATCH 02/16] add columns --- .../edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt | 4 ++++ .../idatt/backend/game/tasks/domain/TaskItemTranslation.kt | 2 ++ 2 files changed, 6 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt index 8b884df0..3ef8ad9c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt @@ -33,6 +33,10 @@ class TaskItem( var mediaUrl: String? = null, @Column(name = "metadata_json") var metadataJson: String? = null, + @Column(name = "is_correct_selection", nullable = false) + var isCorrectSelection: Boolean = false, + @Column(name = "selection_explanation_text") + var selectionExplanationText: String? = null, @OneToMany( mappedBy = "taskItem", cascade = [CascadeType.ALL], diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt index 48e4a78e..b942bbda 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt @@ -30,6 +30,8 @@ class TaskItemTranslation( var locale: TaskLocale = TaskLocale.NB, @Column(name = "prompt_text", nullable = false) var promptText: String = "", + @Column(name = "selection_explanation_text") + var selectionExplanationText: String? = null, ) /** From 4b381ae4cdda75d9c019cdbe77ec531fbce729b4 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:09:16 +0200 Subject: [PATCH 03/16] more columns --- .../game/tasks/application/TaskModels.kt | 42 +++ .../game/tasks/application/TaskService.kt | 323 +++++++++++++++++- 2 files changed, 360 insertions(+), 5 deletions(-) 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 33d7738a..b208dec5 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 @@ -38,6 +38,8 @@ data class ReplaceTaskItemCommand( val promptText: LocalizedText, val mediaUrl: String?, val metadataJson: String?, + val isCorrectSelection: Boolean, + val selectionExplanationText: LocalizedOptionalText?, val options: List, ) @@ -96,6 +98,8 @@ data class TaskItemDetails( val promptText: LocalizedText, val mediaUrl: String?, val metadataJson: String?, + val isCorrectSelection: Boolean, + val selectionExplanationText: LocalizedOptionalText?, val options: List, ) @@ -134,3 +138,41 @@ data class TaskSummary( val itemCount: Int, val updatedAt: Instant?, ) + +data class SubmitStopAnswersCommand( + val authenticatedSubject: String, + val classroomId: Long, + val stopId: Long, + val taskAnswers: List, +) + +data class SubmitTaskAnswerCommand( + val taskId: Long, + val selectedItemId: Long?, + val itemAnswers: List, +) + +data class SubmitItemAnswerCommand( + val itemId: Long, + val selectedOptionId: Long, +) + +data class StopSubmissionResult( + val stopId: Long, + val passed: Boolean, + val score: Int, + val maxScore: Int, + val stopStatus: String, + val completedAt: Instant?, + val taskResults: List, +) + +data class TaskSubmissionResult( + val taskId: Long, + val title: LocalizedText, + val passed: Boolean, + val score: Int, + val maxScore: Int, + val selectedItemId: Long?, + val feedbackText: LocalizedOptionalText?, +) 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 e7f75639..7c7e1c75 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 @@ -2,9 +2,9 @@ package edu.ntnu.idi.idatt.backend.game.tasks.application import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository -import edu.ntnu.idi.idatt.backend.iam.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.game.mapstops.application.PupilStopProgressService +import edu.ntnu.idi.idatt.backend.game.mapstops.application.UpdateStopProgressCommand +import edu.ntnu.idi.idatt.backend.game.mapstops.domain.StopProgressStatus import edu.ntnu.idi.idatt.backend.game.tasks.domain.Task import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskItem import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskItemTranslation @@ -17,6 +17,9 @@ import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskPassingRule import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskTranslation import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskTranslationId import edu.ntnu.idi.idatt.backend.game.tasks.infrastructure.TaskRepository +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 org.springframework.dao.DataIntegrityViolationException import org.springframework.http.HttpStatus import org.springframework.stereotype.Service @@ -31,6 +34,7 @@ class TaskService( private val taskRepository: TaskRepository, private val classroomRepository: ClassroomRepository, private val currentUserResolver: CurrentUserResolver, + private val pupilStopProgressService: PupilStopProgressService, ) { @Transactional(readOnly = true) fun listTasks( @@ -165,6 +169,67 @@ class TaskService( taskRepository.delete(task) } + @Transactional + fun submitStopAnswers(command: SubmitStopAnswersCommand): StopSubmissionResult { + val (_, user) = requireParticipatingClassroom(command.authenticatedSubject, command.classroomId) + if (user.role != UserRole.PUPIL) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Only pupils may submit stop answers") + } + + val pupilId = requireNotNull(user.id) { "Authenticated pupil is missing an id" } + val progress = pupilStopProgressService.getProgressForStop(pupilId, command.classroomId, command.stopId) + if (progress.status == StopProgressStatus.LOCKED) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Stop is locked") + } + + val tasks = taskRepository.findAllByClassroomIdAndStopIdOrderByDifficultyLevelAsc(command.classroomId, command.stopId) + .filter { it.isPublished } + + if (tasks.isEmpty()) { + throw ResponseStatusException(HttpStatus.NOT_FOUND, "No published tasks found for stop") + } + + val answersByTaskId = command.taskAnswers.associateBy { it.taskId } + val expectedTaskIds = tasks.map { requireNotNull(it.id) }.toSet() + val unexpectedTaskIds = answersByTaskId.keys - expectedTaskIds + if (unexpectedTaskIds.isNotEmpty()) { + throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Submitted answers include tasks outside the requested stop", + ) + } + + val taskResults = tasks.map { task -> + val taskId = requireNotNull(task.id) + val taskAnswer = answersByTaskId[taskId] + ?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing answer for task $taskId") + evaluateTaskSubmission(task, taskAnswer) + } + + val totalScore = taskResults.sumOf { it.score } + val totalMaxScore = tasks.sumOf { it.maxScore } + val passed = taskResults.all { it.passed } + val updatedProgress = updateProgressAfterSubmission( + pupilId = pupilId, + classroomId = command.classroomId, + stopId = command.stopId, + currentStatus = progress.status, + score = totalScore, + passed = passed, + firstFailedTaskId = taskResults.firstOrNull { !it.passed }?.taskId, + ) + + return StopSubmissionResult( + stopId = command.stopId, + passed = passed, + score = totalScore, + maxScore = totalMaxScore, + stopStatus = updatedProgress.status.name, + completedAt = updatedProgress.completedAt, + taskResults = taskResults, + ) + } + private fun requireOwnedClassroom(authenticatedSubject: String, classroomId: Long): Classroom { val user = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) val userId = requireNotNull(user.id) { "Authenticated user is missing an id" } @@ -185,7 +250,7 @@ class TaskService( .orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") } - + val hasAccess = when (user.role) { UserRole.ADMIN -> true UserRole.TEACHER -> classroom.ownerTeacherId == userId @@ -245,8 +310,10 @@ class TaskService( promptText = itemCommand.promptText.nb.trim(), mediaUrl = itemCommand.mediaUrl?.trim()?.takeIf { it.isNotBlank() }, metadataJson = itemCommand.metadataJson?.trim()?.takeIf { it.isNotBlank() }, + isCorrectSelection = itemCommand.isCorrectSelection, + selectionExplanationText = itemCommand.selectionExplanationText?.nb?.trim()?.takeIf { it.isNotBlank() }, ) - replaceItemTranslations(item, itemCommand.promptText) + replaceItemTranslations(item, itemCommand.promptText, itemCommand.selectionExplanationText) itemCommand.options.sortedBy { it.optionOrder }.forEach { optionCommand -> val option = TaskOption( optionOrder = optionCommand.optionOrder, @@ -264,6 +331,7 @@ class TaskService( private fun replaceItemTranslations( item: TaskItem, promptText: LocalizedText, + selectionExplanationText: LocalizedOptionalText?, ) { item.translations.clear() item.addTranslation( @@ -271,6 +339,7 @@ class TaskService( id = TaskItemTranslationId(locale = TaskLocale.NB), locale = TaskLocale.NB, promptText = promptText.nb.trim(), + selectionExplanationText = selectionExplanationText?.nb?.trim()?.takeIf { it.isNotBlank() }, ), ) item.addTranslation( @@ -278,6 +347,7 @@ class TaskService( id = TaskItemTranslationId(locale = TaskLocale.EN), locale = TaskLocale.EN, promptText = promptText.en.trim(), + selectionExplanationText = selectionExplanationText?.en?.trim()?.takeIf { it.isNotBlank() }, ), ) } @@ -367,6 +437,23 @@ class TaskService( throw ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Published tasks must include at least one item") } + val itemSelectionMode = task.items.all { it.options.isEmpty() } + if (itemSelectionMode) { + if (task.items.size < 2) { + throw ResponseStatusException( + HttpStatus.UNPROCESSABLE_ENTITY, + "Item-selection tasks must include at least two items", + ) + } + if (task.items.count { it.isCorrectSelection } != 1) { + throw ResponseStatusException( + HttpStatus.UNPROCESSABLE_ENTITY, + "Item-selection tasks must mark exactly one item as correct", + ) + } + return + } + task.items.forEach { item -> if (item.options.size < 2) { throw ResponseStatusException( @@ -383,6 +470,224 @@ class TaskService( } } + private fun evaluateTaskSubmission( + task: Task, + taskAnswer: SubmitTaskAnswerCommand, + ): TaskSubmissionResult = + if (task.items.all { it.options.isEmpty() }) { + evaluateItemSelectionTask(task, taskAnswer) + } else { + evaluateOptionBasedTask(task, taskAnswer) + } + + private fun evaluateItemSelectionTask( + task: Task, + taskAnswer: SubmitTaskAnswerCommand, + ): TaskSubmissionResult { + if (taskAnswer.itemAnswers.isNotEmpty()) { + throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Task ${requireNotNull(task.id)} expects selectedItemId, not per-item option answers", + ) + } + + val selectedItemId = taskAnswer.selectedItemId + ?: throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Task ${requireNotNull(task.id)} is missing selectedItemId", + ) + val selectedItem = task.items.firstOrNull { it.id == selectedItemId } + ?: throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Selected item $selectedItemId does not belong to task ${requireNotNull(task.id)}", + ) + + if (task.items.count { it.isCorrectSelection } != 1) { + throw ResponseStatusException( + HttpStatus.UNPROCESSABLE_ENTITY, + "Task ${requireNotNull(task.id)} is not configured with exactly one correct item", + ) + } + + val score = if (selectedItem.isCorrectSelection) task.maxScore else 0 + return TaskSubmissionResult( + taskId = requireNotNull(task.id), + title = task.resolveTitle(), + passed = passesTask(task, score), + score = score, + maxScore = task.maxScore, + selectedItemId = selectedItemId, + feedbackText = selectedItem.resolveSelectionExplanationText().takeIf { + it.nb != null || it.en != null + }, + ) + } + + private fun evaluateOptionBasedTask( + task: Task, + taskAnswer: SubmitTaskAnswerCommand, + ): TaskSubmissionResult { + if (taskAnswer.selectedItemId != null) { + throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Task ${requireNotNull(task.id)} expects per-item option answers, not selectedItemId", + ) + } + + val answerByItemId = taskAnswer.itemAnswers.associateBy { it.itemId } + val expectedItemIds = task.items.mapNotNull { it.id }.toSet() + val unexpectedItemIds = answerByItemId.keys - expectedItemIds + if (unexpectedItemIds.isNotEmpty()) { + throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Submitted answers include items outside task ${requireNotNull(task.id)}", + ) + } + + val baseItemScore = if (task.items.isEmpty()) 0 else task.maxScore / task.items.size + var score = 0 + val feedback = mutableListOf() + + task.items.forEach { item -> + val itemId = requireNotNull(item.id) + val itemAnswer = answerByItemId[itemId] + ?: throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Missing answer for item $itemId in task ${requireNotNull(task.id)}", + ) + val selectedOption = item.options.firstOrNull { it.id == itemAnswer.selectedOptionId } + ?: throw ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Selected option ${itemAnswer.selectedOptionId} does not belong to item $itemId", + ) + if (selectedOption.isCorrect) { + score += baseItemScore + } else { + selectedOption.resolveExplanationText() + .takeIf { it.nb != null || it.en != null } + ?.let(feedback::add) + } + } + + if (feedback.isEmpty()) { + score = task.maxScore + } + + return TaskSubmissionResult( + taskId = requireNotNull(task.id), + title = task.resolveTitle(), + passed = passesTask(task, score), + score = score, + maxScore = task.maxScore, + selectedItemId = null, + feedbackText = combineFeedback(feedback), + ) + } + + private fun passesTask(task: Task, score: Int): Boolean = + when (task.passingRule) { + TaskPassingRule.ALL_CORRECT -> score >= task.maxScore + TaskPassingRule.MINIMUM_SCORE -> score >= (task.passingScore ?: 0) + } + + private fun updateProgressAfterSubmission( + pupilId: Long, + classroomId: Long, + stopId: Long, + currentStatus: StopProgressStatus, + score: Int, + passed: Boolean, + firstFailedTaskId: Long?, + ) = + when { + passed && currentStatus == StopProgressStatus.NOT_STARTED -> { + pupilStopProgressService.updateProgress( + pupilId, + classroomId, + stopId, + UpdateStopProgressCommand( + status = StopProgressStatus.IN_PROGRESS, + currentTaskId = null, + bestScore = score, + medalAwarded = null, + ), + ) + pupilStopProgressService.updateProgress( + pupilId, + classroomId, + stopId, + UpdateStopProgressCommand( + status = StopProgressStatus.COMPLETED, + currentTaskId = null, + bestScore = score, + medalAwarded = true, + ), + ) + } + + passed && currentStatus == StopProgressStatus.IN_PROGRESS -> pupilStopProgressService.updateProgress( + pupilId, + classroomId, + stopId, + UpdateStopProgressCommand( + status = StopProgressStatus.COMPLETED, + currentTaskId = null, + bestScore = score, + medalAwarded = true, + ), + ) + + passed -> pupilStopProgressService.updateProgress( + pupilId, + classroomId, + stopId, + UpdateStopProgressCommand( + status = null, + currentTaskId = null, + bestScore = score, + medalAwarded = true, + ), + ) + + currentStatus == StopProgressStatus.NOT_STARTED -> pupilStopProgressService.updateProgress( + pupilId, + classroomId, + stopId, + UpdateStopProgressCommand( + status = StopProgressStatus.IN_PROGRESS, + currentTaskId = firstFailedTaskId, + bestScore = score, + medalAwarded = null, + ), + ) + + else -> pupilStopProgressService.updateProgress( + pupilId, + classroomId, + stopId, + UpdateStopProgressCommand( + status = null, + currentTaskId = firstFailedTaskId, + bestScore = score, + medalAwarded = null, + ), + ) + } + + private fun combineFeedback(values: List): LocalizedOptionalText? { + if (values.isEmpty()) return null + return LocalizedOptionalText( + nb = values.mapNotNull { it.nb?.trim()?.takeIf(String::isNotBlank) } + .distinct() + .takeIf { it.isNotEmpty() } + ?.joinToString("\n\n"), + en = values.mapNotNull { it.en?.trim()?.takeIf(String::isNotBlank) } + .distinct() + .takeIf { it.isNotEmpty() } + ?.joinToString("\n\n"), + ) + } + private fun requireUniquePositiveOrders(values: List, fieldName: String) { if (values.any { it <= 0 }) { throw ResponseStatusException(HttpStatus.BAD_REQUEST, "$fieldName must be greater than zero") @@ -435,6 +740,8 @@ private fun Task.toDetails(): TaskDetails = promptText = item.resolvePromptText(), mediaUrl = item.mediaUrl, metadataJson = item.metadataJson, + isCorrectSelection = item.isCorrectSelection, + selectionExplanationText = item.resolveSelectionExplanationText(), options = item.options.sortedBy { it.optionOrder }.map { option -> TaskOptionDetails( id = requireNotNull(option.id), @@ -466,6 +773,12 @@ private fun TaskItem.resolvePromptText(): LocalizedText = en = translations.firstOrNull { it.locale == TaskLocale.EN }?.promptText ?: promptText, ) +private fun TaskItem.resolveSelectionExplanationText(): LocalizedOptionalText = + LocalizedOptionalText( + nb = translations.firstOrNull { it.locale == TaskLocale.NB }?.selectionExplanationText ?: selectionExplanationText, + en = translations.firstOrNull { it.locale == TaskLocale.EN }?.selectionExplanationText ?: selectionExplanationText, + ) + private fun TaskOption.resolveOptionText(): LocalizedText = LocalizedText( nb = translations.firstOrNull { it.locale == TaskLocale.NB }?.optionText ?: optionText, From cb8cd3c2b48bfb66e681c428f4c4f90e24cb1446 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:09:31 +0200 Subject: [PATCH 04/16] api --- .../backend/game/tasks/api/TaskApiMappings.kt | 26 ++++++++++ .../backend/game/tasks/api/TaskController.kt | 8 ++++ .../backend/game/tasks/api/TaskRequests.kt | 48 +++++++++++++++++++ .../backend/game/tasks/api/TaskResponses.kt | 23 +++++++++ 4 files changed, 105 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt index 2f019e01..bc17cf1f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt @@ -2,7 +2,9 @@ package edu.ntnu.idi.idatt.backend.game.tasks.api import edu.ntnu.idi.idatt.backend.game.tasks.application.LocalizedOptionalText import edu.ntnu.idi.idatt.backend.game.tasks.application.LocalizedText +import edu.ntnu.idi.idatt.backend.game.tasks.application.StopSubmissionResult import edu.ntnu.idi.idatt.backend.game.tasks.application.TaskDetails +import edu.ntnu.idi.idatt.backend.game.tasks.application.TaskSubmissionResult import edu.ntnu.idi.idatt.backend.game.tasks.application.TaskSummary /** @@ -50,6 +52,8 @@ fun TaskDetails.toResponse(includeAnswers: Boolean = true): TaskResponse = promptText = item.promptText.toResponse(), mediaUrl = item.mediaUrl, metadataJson = item.metadataJson, + isCorrectSelection = item.isCorrectSelection.takeIf { includeAnswers }, + selectionExplanationText = item.selectionExplanationText?.takeIf { includeAnswers }?.toResponse(), options = item.options.map { option -> TaskOptionResponse( id = option.id, @@ -68,3 +72,25 @@ private fun LocalizedText.toResponse(): LocalizedTextResponse = private fun LocalizedOptionalText.toResponse(): LocalizedOptionalTextResponse = LocalizedOptionalTextResponse(nb = nb, en = en) + +fun StopSubmissionResult.toResponse(): StopSubmissionResponse = + StopSubmissionResponse( + stopId = stopId, + passed = passed, + score = score, + maxScore = maxScore, + stopStatus = stopStatus, + completedAt = completedAt, + taskResults = taskResults.map { it.toResponse() }, + ) + +private fun TaskSubmissionResult.toResponse(): TaskSubmissionResultResponse = + TaskSubmissionResultResponse( + taskId = taskId, + title = title.toResponse(), + passed = passed, + score = score, + maxScore = maxScore, + selectedItemId = selectedItemId, + feedbackText = feedbackText?.toResponse(), + ) 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 fe5594ee..a24a9b27 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 @@ -51,6 +51,14 @@ class TaskController( .getTask(currentUser.subject, classroomId, taskId) .toResponse(includeAnswers = currentUser.portalType != "PUPIL") + @PostMapping("/submit-stop") + fun submitStopAnswers( + @PathVariable classroomId: Long, + @RequestBody @Valid request: SubmitStopAnswersRequest, + @AuthenticationPrincipal currentUser: CurrentUser, + ): StopSubmissionResponse = + taskService.submitStopAnswers(request.toCommand(classroomId, currentUser.subject)).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 7b284e3f..54bd3040 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 @@ -56,10 +56,35 @@ data class TaskItemRequest( var promptText: LocalizedRequiredTextRequest, val mediaUrl: String? = null, val metadataJson: String? = null, + val isCorrectSelection: Boolean = false, + @field:Valid + val selectionExplanationText: LocalizedOptionalTextRequest? = null, @field:Valid val options: List = emptyList(), ) +data class SubmitStopAnswersRequest( + @field:Min(1) + val stopId: Long, + @field:Valid + val taskAnswers: List = emptyList(), +) + +data class SubmitTaskAnswerRequest( + @field:Min(1) + val taskId: Long, + val selectedItemId: Long? = null, + @field:Valid + val itemAnswers: List = emptyList(), +) + +data class SubmitItemAnswerRequest( + @field:Min(1) + val itemId: Long, + @field:Min(1) + val selectedOptionId: Long, +) + /** * Request payload for creating a new task inside one classroom. */ @@ -168,6 +193,8 @@ private fun List.toCommands(): List = promptText = item.promptText.toLocalizedText(), mediaUrl = item.mediaUrl, metadataJson = item.metadataJson, + isCorrectSelection = item.isCorrectSelection, + selectionExplanationText = item.selectionExplanationText?.toLocalizedOptionalText(), options = item.options.map { option -> ReplaceTaskOptionCommand( optionOrder = option.optionOrder, @@ -184,3 +211,24 @@ private fun LocalizedRequiredTextRequest.toLocalizedText(): LocalizedText = private fun LocalizedOptionalTextRequest.toLocalizedOptionalText(): LocalizedOptionalText = LocalizedOptionalText(nb = nb, en = en) + +fun SubmitStopAnswersRequest.toCommand( + classroomId: Long, + authenticatedSubject: String, +) = edu.ntnu.idi.idatt.backend.game.tasks.application.SubmitStopAnswersCommand( + authenticatedSubject = authenticatedSubject, + classroomId = classroomId, + stopId = stopId, + taskAnswers = taskAnswers.map { taskAnswer -> + edu.ntnu.idi.idatt.backend.game.tasks.application.SubmitTaskAnswerCommand( + taskId = taskAnswer.taskId, + selectedItemId = taskAnswer.selectedItemId, + itemAnswers = taskAnswer.itemAnswers.map { itemAnswer -> + edu.ntnu.idi.idatt.backend.game.tasks.application.SubmitItemAnswerCommand( + itemId = itemAnswer.itemId, + selectedOptionId = itemAnswer.selectedOptionId, + ) + }, + ) + }, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt index c2e14a64..fd60b941 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt @@ -36,12 +36,15 @@ data class TaskOptionResponse( /** * Serialized prompt item returned from task endpoints. */ +@JsonInclude(JsonInclude.Include.NON_NULL) data class TaskItemResponse( val id: Long, val itemOrder: Int, val promptText: LocalizedTextResponse, val mediaUrl: String?, val metadataJson: String?, + val isCorrectSelection: Boolean?, + val selectionExplanationText: LocalizedOptionalTextResponse?, val options: List, ) @@ -80,3 +83,23 @@ data class TaskSummaryResponse( val itemCount: Int, val updatedAt: Instant?, ) + +data class TaskSubmissionResultResponse( + val taskId: Long, + val title: LocalizedTextResponse, + val passed: Boolean, + val score: Int, + val maxScore: Int, + val selectedItemId: Long?, + val feedbackText: LocalizedOptionalTextResponse?, +) + +data class StopSubmissionResponse( + val stopId: Long, + val passed: Boolean, + val score: Int, + val maxScore: Int, + val stopStatus: String, + val completedAt: Instant?, + val taskResults: List, +) From 1557809e5a9dc96071f18f3fc20a28138de57153 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:09:35 +0200 Subject: [PATCH 05/16] api test --- .../game/tasks/TaskApiIntegrationTests.kt | 218 ++++++++++++++++++ 1 file changed, 218 insertions(+) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt index ef9e232b..96f2ae49 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt @@ -10,6 +10,12 @@ 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.RefreshTokenRepository import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +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.mapstops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgressRepository import edu.ntnu.idi.idatt.backend.game.tasks.infrastructure.TaskRepository import edu.ntnu.idi.idatt.backend.users.avatar.infrastructure.UserAvatarRepository import edu.ntnu.idi.idatt.backend.users.profile.infrastructure.PupilProfileRepository @@ -46,6 +52,12 @@ class TaskApiIntegrationTests { @Autowired private lateinit var taskRepository: TaskRepository + @Autowired + private lateinit var mapStopsRepository: MapStopsRepository + + @Autowired + private lateinit var pupilStopProgressRepository: PupilStopProgressRepository + @Autowired private lateinit var refreshTokenRepository: RefreshTokenRepository @@ -66,7 +78,9 @@ class TaskApiIntegrationTests { @BeforeEach fun setUp() { refreshTokenRepository.deleteAll() + pupilStopProgressRepository.deleteAll() taskRepository.deleteAll() + mapStopsRepository.deleteAll() classroomRepository.deleteAll() userAvatarRepository.deleteAll() pupilProfileRepository.deleteAll() @@ -314,6 +328,144 @@ class TaskApiIntegrationTests { } } + @Test + fun `pupil can submit wrong stop answers and receive task feedback`() { + val owner = userRepository.save(activeTeacher("owner@example.com")) + val classroom = createClassroom(owner, "TASK48") + val stop = createMapStop(slug = "nyhetskvartalet", title = "News Quarter", displayOrder = 1) + val teacherAccessToken = teacherAccessToken("owner@example.com", "secret123") + + val createdBody = readJson( + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = itemSelectionTaskPayload(stopId = requireNotNull(stop.id)) + }.andExpect { + status { isCreated() } + }.andReturn().response.contentAsString, + ) + val taskId = createdBody.get("id").asLong() + val wrongItemId = createdBody.get("items")[0].get("id").asLong() + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = """{"published":true}""" + }.andExpect { + status { isOk() } + } + + val pupil = userRepository.save(activePupil("submitter_wrong")) + classroom.addPupilMembership(pupil) + classroomRepository.saveAndFlush(classroom) + createStopProgress(pupil, classroom, stop, StopProgressStatus.NOT_STARTED) + val pupilAccessToken = pupilAccessToken("submitter_wrong", "secret123") + + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks/submit-stop") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilAccessToken") + content = """ + { + "stopId": ${requireNotNull(stop.id)}, + "taskAnswers": [ + { + "taskId": $taskId, + "selectedItemId": $wrongItemId + } + ] + } + """.trimIndent() + }.andExpect { + status { isOk() } + jsonPath("$.passed") { value(false) } + jsonPath("$.stopStatus") { value("IN_PROGRESS") } + jsonPath("$.taskResults[0].passed") { value(false) } + jsonPath("$.taskResults[0].selectedItemId") { value(wrongItemId) } + jsonPath("$.taskResults[0].feedbackText.en") { + value("This article uses sensational language and makes unsupported claims.") + } + } + + val progress = pupilStopProgressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId( + requireNotNull(pupil.id), + requireNotNull(classroom.id), + requireNotNull(stop.id), + ) + assertEquals(StopProgressStatus.IN_PROGRESS, progress?.status) + assertEquals(taskId, progress?.currentTaskId) + } + + @Test + fun `pupil can submit correct stop answers and complete the stop`() { + val owner = userRepository.save(activeTeacher("owner@example.com")) + val classroom = createClassroom(owner, "TASK49") + val stop = createMapStop(slug = "nyhetskvartalet", title = "News Quarter", displayOrder = 1) + val teacherAccessToken = teacherAccessToken("owner@example.com", "secret123") + + val createdBody = readJson( + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = itemSelectionTaskPayload(stopId = requireNotNull(stop.id)) + }.andExpect { + status { isCreated() } + }.andReturn().response.contentAsString, + ) + val taskId = createdBody.get("id").asLong() + val correctItemId = createdBody.get("items")[1].get("id").asLong() + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = """{"published":true}""" + }.andExpect { + status { isOk() } + } + + val pupil = userRepository.save(activePupil("submitter_correct")) + classroom.addPupilMembership(pupil) + classroomRepository.saveAndFlush(classroom) + createStopProgress(pupil, classroom, stop, StopProgressStatus.NOT_STARTED) + val pupilAccessToken = pupilAccessToken("submitter_correct", "secret123") + + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks/submit-stop") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilAccessToken") + content = """ + { + "stopId": ${requireNotNull(stop.id)}, + "taskAnswers": [ + { + "taskId": $taskId, + "selectedItemId": $correctItemId + } + ] + } + """.trimIndent() + }.andExpect { + status { isOk() } + jsonPath("$.passed") { value(true) } + jsonPath("$.score") { value(100) } + jsonPath("$.stopStatus") { value("COMPLETED") } + jsonPath("$.taskResults[0].passed") { value(true) } + } + + val progress = pupilStopProgressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId( + requireNotNull(pupil.id), + requireNotNull(classroom.id), + requireNotNull(stop.id), + ) + assertEquals(StopProgressStatus.COMPLETED, progress?.status) + assertEquals(100, progress?.bestScore) + assertEquals(true, progress?.medalAwarded) + } + private fun createClassroom(owner: User, joinCode: String): Classroom = classroomRepository.save( Classroom( @@ -325,6 +477,34 @@ class TaskApiIntegrationTests { ), ) + private fun createMapStop(slug: String, title: String, displayOrder: Int): MapStop = + mapStopsRepository.save( + MapStop( + slug = slug, + title = title, + displayOrder = displayOrder, + maxScore = 100, + isActive = true, + ), + ) + + private fun createStopProgress( + pupil: User, + classroom: Classroom, + stop: MapStop, + status: StopProgressStatus, + ): PupilStopProgress = + pupilStopProgressRepository.save( + PupilStopProgress( + id = PupilStopProgressId(requireNotNull(pupil.id), requireNotNull(classroom.id), requireNotNull(stop.id)), + pupil = pupil, + classroom = classroom, + stop = stop, + ).apply { + this.status = status + }, + ) + private fun teacherAccessToken(email: String, password: String): String = readJson( mockMvc.post("/api/v1/auth/teacher/login") { @@ -402,4 +582,42 @@ class TaskApiIntegrationTests { ] } """.trimIndent() + + private fun itemSelectionTaskPayload(stopId: Long): String = + """ + { + "stopId": $stopId, + "title": {"nb":"Finn den troverdige artikkelen","en":"Find the trustworthy article"}, + "introText": {"nb":"Velg artikkelen som er mest troverdig.","en":"Pick the article that is most trustworthy."}, + "difficultyLevel": 1, + "taskType": "NEWS_COMPARISON", + "passingRule": "ALL_CORRECT", + "passingScore": 100, + "maxScore": 100, + "items": [ + { + "itemOrder": 1, + "promptText": {"nb":"Sensasjonell artikkel","en":"Sensational article"}, + "metadataJson": "{\"domain\":\"clickbait.example\"}", + "isCorrectSelection": false, + "selectionExplanationText": { + "nb":"Denne artikkelen bruker sensasjonelt språk og udokumenterte påstander.", + "en":"This article uses sensational language and makes unsupported claims." + }, + "options": [] + }, + { + "itemOrder": 2, + "promptText": {"nb":"Nøktern artikkel","en":"Measured article"}, + "metadataJson": "{\"domain\":\"news.example\"}", + "isCorrectSelection": true, + "selectionExplanationText": { + "nb":"Denne artikkelen oppgir kilde og forklarer fakta på en etterprøvbar måte.", + "en":"This article names its source and explains the facts in a verifiable way." + }, + "options": [] + } + ] + } + """.trimIndent() } From 632e1ff691901d6960c2da480bfea96e9f481b77 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:09:39 +0200 Subject: [PATCH 06/16] update bootstrap --- .../backend/bootstrap/DevDataBootstrap.kt | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) 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 97186f9e..edd543db 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 @@ -445,8 +445,10 @@ class DevDataBootstrap( promptText = itemSeed.promptText.nb, mediaUrl = itemSeed.mediaUrl, metadataJson = itemSeed.metadataJson, + isCorrectSelection = itemSeed.isCorrectSelection, + selectionExplanationText = itemSeed.selectionExplanationText?.nb, ) - addItemTranslations(item, itemSeed.promptText) + addItemTranslations(item, itemSeed.promptText, itemSeed.selectionExplanationText) itemSeed.options.forEach { optionSeed -> val option = TaskOption( optionOrder = optionSeed.optionOrder, @@ -487,12 +489,14 @@ class DevDataBootstrap( private fun addItemTranslations( item: TaskItem, promptText: LocalizedText, + selectionExplanationText: LocalizedOptionalText?, ) { item.addTranslation( TaskItemTranslation( id = TaskItemTranslationId(locale = TaskLocale.NB), locale = TaskLocale.NB, promptText = promptText.nb, + selectionExplanationText = selectionExplanationText?.nb, ), ) item.addTranslation( @@ -500,6 +504,7 @@ class DevDataBootstrap( id = TaskItemTranslationId(locale = TaskLocale.EN), locale = TaskLocale.EN, promptText = promptText.en, + selectionExplanationText = selectionExplanationText?.en, ), ) } @@ -545,6 +550,10 @@ class DevDataBootstrap( "UNBELIEVABLE! Research proves chocolate is healthy!\n\nA groundbreaking new study has FINALLY proven what we all hoped: chocolate is just as healthy as - or perhaps even healthier than - vegetables! The doctor who led the research was surprised by the results.\n\n\"We cannot believe what we are seeing. Chocolate cures almost everything,\" an anonymous researcher allegedly said.\n\nExperts worldwide are now in shock. It is recommended to eat at least 200 grams of chocolate daily to stay healthy. Vegetables can safely be dropped!\nShare this article with everyone you know BEFORE the authorities censor it - Big Pharma does not want you to know this!", ), metadataJson = """{"domain":"helserevolusjonen.no"}""", + selectionExplanationText = localizedOptional( + "Denne saken bruker sensasjonelt språk, anonyme kilder og overdrevne påstander uten troverdige bevis.", + "This story uses sensational language, anonymous sources, and exaggerated claims without credible evidence.", + ), options = emptyList(), ), SeedItem( @@ -555,6 +564,11 @@ class DevDataBootstrap( ), mediaUrl = "https://images.unsplash.com/photo-1481391319762-47dff72954d9?w=600&q=80", metadataJson = """{"domain":"forskning.no"}""", + isCorrectSelection = true, + selectionExplanationText = localizedOptional( + "Denne saken viser til en konkret studie, oppgir kilde og forklarer begrensningene i funnene.", + "This story cites a concrete study, names the source, and explains the limits of the findings.", + ), options = emptyList(), ), ), @@ -575,6 +589,10 @@ class DevDataBootstrap( "YOUR DOCTOR NEVER TOLD YOU THIS! One simple thing cures all diseases\n\nThe pharmaceutical industry is hiding a secret that could change your life. An unknown doctor recently revealed you NEVER have to get sick again. Click here to find out what Big Pharma does not want you to know.", ), metadataJson = """{"domain":"helseavsloringer.net"}""", + selectionExplanationText = localizedOptional( + "Denne saken bruker clickbait, sterke følelsesord og udokumenterte påstander for å lokke deg til å klikke.", + "This story uses clickbait, emotional language, and unsupported claims to make you click.", + ), options = emptyList(), ), SeedItem( @@ -584,6 +602,11 @@ class DevDataBootstrap( "New report: Regular exercise reduces risk of cardiovascular disease\n\nThe Norwegian Institute of Public Health today presented a new report showing that 150 minutes of moderate physical activity per week is associated with a 35 percent lower risk of heart attack in adults over 40. The report is based on data from over 50,000 Norwegians followed over ten years.", ), metadataJson = """{"domain":"fhi.no"}""", + isCorrectSelection = true, + selectionExplanationText = localizedOptional( + "Denne saken bruker nøkternt språk, oppgir avsender og beskriver datagrunnlaget på en etterprøvbar måte.", + "This story uses neutral language, names the source, and describes the evidence in a verifiable way.", + ), options = emptyList(), ), ), @@ -604,6 +627,11 @@ class DevDataBootstrap( "Three classes tested their reading times for two weeks and wrote down the results.", ), metadataJson = null, + isCorrectSelection = true, + selectionExplanationText = localizedOptional( + "Denne teksten beskriver observerbare fakta uten å presse fram en følelsesmessig reaksjon.", + "This text describes observable facts without trying to force an emotional reaction.", + ), options = emptyList(), ), SeedItem( @@ -613,6 +641,10 @@ class DevDataBootstrap( "Everyone is furious after the incredibly scary news spreading everywhere.", ), metadataJson = null, + selectionExplanationText = localizedOptional( + "Denne teksten bruker følelsesladde ord som 'rasende' og 'skumle' i stedet for konkrete fakta.", + "This text uses emotional words like 'furious' and 'scary' instead of concrete facts.", + ), options = emptyList(), ), ), @@ -1276,6 +1308,8 @@ class DevDataBootstrap( val promptText: LocalizedText, val mediaUrl: String? = null, val metadataJson: String? = null, + val isCorrectSelection: Boolean = false, + val selectionExplanationText: LocalizedOptionalText? = null, val options: List, ) From 9c5c5858b0474f4fff2afb716e08a19454c37421 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:49:18 +0200 Subject: [PATCH 07/16] load max score from task repository --- .../mapstops/application/MapStopService.kt | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt index bb1907b5..5eb65fb7 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt @@ -4,6 +4,7 @@ import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop 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.game.tasks.infrastructure.TaskRepository import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.web.server.ResponseStatusException @@ -18,6 +19,7 @@ import org.springframework.web.server.ResponseStatusException class MapStopService( private val mapStopsRepository: MapStopsRepository, private val pupilStopProgressRepository: PupilStopProgressRepository, + private val taskRepository: TaskRepository, ) { /** * Returns all active map stops sorted by display order. @@ -52,10 +54,12 @@ class MapStopService( val progressByStopId = pupilStopProgressRepository .findAllByIdPupilUserIdAndIdClassroomId(pupilUserId, classroomId) .associateBy { it.id.stopId } + val maxScoreByStopId = loadPublishedStopMaxScores(classroomId) return stops.mapNotNull { stop -> val stopId = stop.id ?: return@mapNotNull null val progress = progressByStopId[stop.id!!] + val maxScore = maxScoreByStopId[stopId] ?: 0 MapStopOverviewEntry( stopId = stopId, slug = stop.slug, @@ -64,7 +68,7 @@ class MapStopService( displayOrder = stop.displayOrder ?: 0, isFinalBoss = stop.isFinalBoss ?: false, status = progress?.status ?: StopProgressStatus.LOCKED, - stars = progress?.let { computeStars(it.bestScore, stop.maxScore ?: 0) } ?: 0, + stars = progress?.let { computeStars(it.bestScore, maxScore) } ?: 0, medalAwarded = progress?.medalAwarded ?: false, ) } @@ -83,6 +87,7 @@ class MapStopService( val stop = getMapStopBySlug(slug) val stopId = stop.id ?: throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Map stop has no id") + val maxScoreByStopId = loadPublishedStopMaxScores(classroomId) val progress = pupilStopProgressRepository .findByIdPupilUserIdAndIdClassroomIdAndIdStopId(pupilUserId, classroomId, stopId) @@ -95,11 +100,18 @@ class MapStopService( displayOrder = stop.displayOrder ?: 0, isFinalBoss = stop.isFinalBoss ?: false, status = progress?.status ?: StopProgressStatus.LOCKED, - stars = progress?.let { computeStars(it.bestScore, stop.maxScore ?: 0) } ?: 0, + stars = progress?.let { computeStars(it.bestScore, maxScoreByStopId[stopId] ?: 0) } ?: 0, medalAwarded = progress?.medalAwarded ?: false, ) } + private fun loadPublishedStopMaxScores(classroomId: Long): Map = + taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(classroomId) + .asSequence() + .filter { it.isPublished } + .groupBy { it.stopId } + .mapValues { (_, tasks) -> tasks.sumOf { it.maxScore } } + private fun computeStars(bestScore: Int, maxScore: Int): Int { if (maxScore == 0) return 0 val ratio = bestScore.toDouble() / maxScore @@ -135,4 +147,4 @@ data class MapStopOverviewEntry( val status: StopProgressStatus, val stars: Int, val medalAwarded: Boolean, -) \ No newline at end of file +) From f0f45a07db568d7a88e8ca36ac0bfab6aaba4831 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:49:53 +0200 Subject: [PATCH 08/16] stop resubmit if completed --- .../idi/idatt/backend/game/tasks/application/TaskService.kt | 3 +++ 1 file changed, 3 insertions(+) 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 7c7e1c75..b18c0cb2 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 @@ -181,6 +181,9 @@ class TaskService( if (progress.status == StopProgressStatus.LOCKED) { throw ResponseStatusException(HttpStatus.FORBIDDEN, "Stop is locked") } + if (progress.status == StopProgressStatus.COMPLETED) { + throw ResponseStatusException(HttpStatus.CONFLICT, "Stop has already been completed") + } val tasks = taskRepository.findAllByClassroomIdAndStopIdOrderByDifficultyLevelAsc(command.classroomId, command.stopId) .filter { it.isPublished } From f1382778f7f4bc3a13145e46dcaef79ba94918ac Mon Sep 17 00:00:00 2001 From: eilifhl Date: Tue, 21 Apr 2026 14:50:02 +0200 Subject: [PATCH 09/16] tests --- .../game/mapstops/MapStopServiceTests.kt | 103 ++++++----- .../game/tasks/TaskApiIntegrationTests.kt | 163 ++++++++++++++++++ 2 files changed, 226 insertions(+), 40 deletions(-) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/MapStopServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/MapStopServiceTests.kt index 1bf2061f..b178f041 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/MapStopServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/MapStopServiceTests.kt @@ -8,6 +8,8 @@ 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.game.tasks.domain.Task +import edu.ntnu.idi.idatt.backend.game.tasks.infrastructure.TaskRepository 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 @@ -19,12 +21,17 @@ import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException class MapStopServiceTests { + private fun serviceWithMocks(): Triple = + Triple( + Mockito.mock(MapStopsRepository::class.java), + Mockito.mock(PupilStopProgressRepository::class.java), + Mockito.mock(TaskRepository::class.java), + ) @Test fun `get all map stops returns active stops in display order`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stops = listOf(mapStop(id = 1L, displayOrder = 1), mapStop(id = 2L, displayOrder = 2)) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(stops) @@ -38,9 +45,8 @@ class MapStopServiceTests { @Test fun `get all map stops returns empty list when no active stops exist`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) @@ -51,9 +57,8 @@ class MapStopServiceTests { @Test fun `get map stop by slug throws 404 when no stop matches`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("not a stop")).thenReturn(null) @@ -66,13 +71,13 @@ class MapStopServiceTests { @Test fun `get map overview falls back to LOCKED when pupil has no progress record for a stop`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 10L, displayOrder = 1) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(emptyList()) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(emptyList()) val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) @@ -84,14 +89,14 @@ class MapStopServiceTests { @Test fun `get map overview reflects pupil progress status and stars when record exists`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 10L, displayOrder = 1, maxScore = 100) val progress = progress(stopId = 10L, status = StopProgressStatus.COMPLETED, bestScore = 80) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(listOf(progress)) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(listOf(publishedTask(stopId = 10L, maxScore = 100))) val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) @@ -101,12 +106,12 @@ class MapStopServiceTests { @Test fun `get map overview returns empty list when there are no active stops`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(emptyList()) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(emptyList()) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(emptyList()) val result = service.getMapOverview(pupilUserId = 1L, classroomId = 2L) @@ -115,15 +120,15 @@ class MapStopServiceTests { @Test fun `get map stop overview by slug returns enriched entry for pupil with progress`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 5L, slug = "data-center", maxScore = 100) val progress = progress(stopId = 5L, status = StopProgressStatus.IN_PROGRESS, bestScore = 50) Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data-center")).thenReturn(stop) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 5L)) .thenReturn(progress) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(listOf(publishedTask(stopId = 5L, maxScore = 100))) val result = service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") @@ -134,14 +139,14 @@ class MapStopServiceTests { @Test fun `get map stop overview by slug falls back to LOCKED when pupil has no progress`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 5L, slug = "data-center") Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data-center")).thenReturn(stop) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 5L)) .thenReturn(null) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(emptyList()) val result = service.getMapStopOverviewBySlug(pupilUserId = 1L, classroomId = 2L, slug = "data-center") @@ -151,9 +156,8 @@ class MapStopServiceTests { @Test fun `get map stop overview by slug throws 404 for unknown slug`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) Mockito.`when`(mapStopsRepository.findBySlugIgnoreCase("data center")).thenReturn(null) @@ -166,56 +170,56 @@ class MapStopServiceTests { @Test fun `get map overview awards 0 stars when best score is below 25 percent of max`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 1L, maxScore = 100) val progress = progress(stopId = 1L, bestScore = 24) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(listOf(progress)) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(listOf(publishedTask(stopId = 1L, maxScore = 100))) assertEquals(0, service.getMapOverview(1L, 2L)[0].stars) } @Test fun `get map overview awards 1 star when best score is exactly 25 percent of max`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 1L, maxScore = 100) val progress = progress(stopId = 1L, bestScore = 25) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(listOf(progress)) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(listOf(publishedTask(stopId = 1L, maxScore = 100))) assertEquals(1, service.getMapOverview(1L, 2L)[0].stars) } @Test fun `get map overview awards 2 stars when best score is exactly 50 percent of max`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 1L, maxScore = 100) val progress = progress(stopId = 1L, bestScore = 50) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(listOf(progress)) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(listOf(publishedTask(stopId = 1L, maxScore = 100))) assertEquals(2, service.getMapOverview(1L, 2L)[0].stars) } @Test fun `get map overview awards 0 stars when max score is zero`() { - val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val service = MapStopService(mapStopsRepository, progressRepository) + val (mapStopsRepository, progressRepository, taskRepository) = serviceWithMocks() + val service = MapStopService(mapStopsRepository, progressRepository, taskRepository) val stop = mapStop(id = 1L, maxScore = 0) val progress = progress(stopId = 1L, bestScore = 100) Mockito.`when`(mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()).thenReturn(listOf(stop)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(listOf(progress)) + Mockito.`when`(taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(2L)).thenReturn(emptyList()) assertEquals(0, service.getMapOverview(1L, 2L)[0].stars) } @@ -261,4 +265,23 @@ class MapStopServiceTests { this.medalAwarded = medalAwarded } } -} \ No newline at end of file + + private fun publishedTask(stopId: Long, maxScore: Int): Task = + Task( + stopId = stopId, + classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom"), + createdByTeacher = User( + id = 2L, + email = "teacher@example.com", + passwordHash = "hash", + role = UserRole.TEACHER, + status = UserStatus.ACTIVE, + ), + title = "Task $stopId", + difficultyLevel = 1, + taskType = edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskType.GENERIC, + passingRule = edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskPassingRule.ALL_CORRECT, + maxScore = maxScore, + isPublished = true, + ) +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt index 96f2ae49..4aa45ee0 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt @@ -466,6 +466,128 @@ class TaskApiIntegrationTests { assertEquals(true, progress?.medalAwarded) } + @Test + fun `completed stop cannot be submitted again`() { + val owner = userRepository.save(activeTeacher("owner@example.com")) + val classroom = createClassroom(owner, "TASK50") + val stop = createMapStop(slug = "nyhetskvartalet", title = "News Quarter", displayOrder = 1) + val teacherAccessToken = teacherAccessToken("owner@example.com", "secret123") + + val createdBody = readJson( + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = itemSelectionTaskPayload(stopId = requireNotNull(stop.id)) + }.andExpect { + status { isCreated() } + }.andReturn().response.contentAsString, + ) + val taskId = createdBody.get("id").asLong() + val correctItemId = createdBody.get("items")[1].get("id").asLong() + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = """{"published":true}""" + }.andExpect { + status { isOk() } + } + + val pupil = userRepository.save(activePupil("submitter_completed")) + classroom.addPupilMembership(pupil) + classroomRepository.saveAndFlush(classroom) + createStopProgress(pupil, classroom, stop, StopProgressStatus.COMPLETED) + val pupilAccessToken = pupilAccessToken("submitter_completed", "secret123") + + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks/submit-stop") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilAccessToken") + content = """ + { + "stopId": ${requireNotNull(stop.id)}, + "taskAnswers": [ + { + "taskId": $taskId, + "selectedItemId": $correctItemId + } + ] + } + """.trimIndent() + }.andExpect { + status { isConflict() } + } + } + + @Test + fun `pupil can submit option based stop answers and receive explanation for wrong option`() { + val owner = userRepository.save(activeTeacher("owner@example.com")) + val classroom = createClassroom(owner, "TASK51") + val stop = createMapStop(slug = "bildekvartalet", title = "Image Quarter", displayOrder = 1) + val teacherAccessToken = teacherAccessToken("owner@example.com", "secret123") + + val createdBody = readJson( + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = optionTaskPayload(stopId = requireNotNull(stop.id)) + }.andExpect { + status { isCreated() } + }.andReturn().response.contentAsString, + ) + val taskId = createdBody.get("id").asLong() + val taskItemId = createdBody.get("items")[0].get("id").asLong() + val wrongOptionId = createdBody.get("items")[0].get("options")[1].get("id").asLong() + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = """{"published":true}""" + }.andExpect { + status { isOk() } + } + + val pupil = userRepository.save(activePupil("submitter_option_wrong")) + classroom.addPupilMembership(pupil) + classroomRepository.saveAndFlush(classroom) + createStopProgress(pupil, classroom, stop, StopProgressStatus.NOT_STARTED) + val pupilAccessToken = pupilAccessToken("submitter_option_wrong", "secret123") + + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks/submit-stop") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilAccessToken") + content = """ + { + "stopId": ${requireNotNull(stop.id)}, + "taskAnswers": [ + { + "taskId": $taskId, + "itemAnswers": [ + { + "itemId": $taskItemId, + "selectedOptionId": $wrongOptionId + } + ] + } + ] + } + """.trimIndent() + }.andExpect { + status { isOk() } + jsonPath("$.passed") { value(false) } + jsonPath("$.stopStatus") { value("IN_PROGRESS") } + jsonPath("$.taskResults[0].passed") { value(false) } + jsonPath("$.taskResults[0].feedbackText.en") { + value("This option ignores the warning signs in the image.") + } + } + } + private fun createClassroom(owner: User, joinCode: String): Classroom = classroomRepository.save( Classroom( @@ -620,4 +742,45 @@ class TaskApiIntegrationTests { ] } """.trimIndent() + + private fun optionTaskPayload(stopId: Long): String = + """ + { + "stopId": $stopId, + "title": {"nb":"Vurder bildet","en":"Assess the image"}, + "introText": {"nb":"Velg vurderingen som passer best.","en":"Choose the assessment that fits best."}, + "difficultyLevel": 1, + "taskType": "IMAGE_ASSESSMENT", + "passingRule": "ALL_CORRECT", + "passingScore": 100, + "maxScore": 100, + "items": [ + { + "itemOrder": 1, + "promptText": {"nb":"Hva er riktig vurdering?","en":"What is the correct assessment?"}, + "metadataJson": "{\"imageUrl\":\"https://example.com/warning-sign.jpg\"}", + "options": [ + { + "optionOrder": 1, + "optionText": {"nb":"Bildet viser tydelige faresignaler.","en":"The image shows clear warning signs."}, + "isCorrect": true, + "explanationText": { + "nb":"Dette er riktig fordi faresignalene er tydelige i motivet.", + "en":"This is correct because the warning signs are clearly visible in the scene." + } + }, + { + "optionOrder": 2, + "optionText": {"nb":"Bildet ser helt trygt ut.","en":"The image looks completely safe."}, + "isCorrect": false, + "explanationText": { + "nb":"Dette alternativet overser faresignalene i bildet.", + "en":"This option ignores the warning signs in the image." + } + } + ] + } + ] + } + """.trimIndent() } From d9e836f9666ae2b2b7613c0dd8e61190ae2b6791 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 10:21:50 +0200 Subject: [PATCH 10/16] rename migration --- ...ion_feedback.sql => V15__add_task_item_selection_feedback.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/main/resources/db/migration/{V13__add_task_item_selection_feedback.sql => V15__add_task_item_selection_feedback.sql} (100%) diff --git a/src/main/resources/db/migration/V13__add_task_item_selection_feedback.sql b/src/main/resources/db/migration/V15__add_task_item_selection_feedback.sql similarity index 100% rename from src/main/resources/db/migration/V13__add_task_item_selection_feedback.sql rename to src/main/resources/db/migration/V15__add_task_item_selection_feedback.sql From acda5a3264fe4f7efdee0264edcc06b3f5d56193 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 10:22:47 +0200 Subject: [PATCH 11/16] clear task id when stop finished --- .../application/PupilStopProgressService.kt | 3 +- .../mapstops/PupilStopProgressServiceTests.kt | 28 ++++++++++++++++++- 2 files changed, 29 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..61fde0ac 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 @@ -87,6 +87,7 @@ class PupilStopProgressService( progress.status = next if (next == StopProgressStatus.COMPLETED && progress.completedAt == null) { + progress.currentTaskId = null progress.completedAt = Instant.now() unlockNextStop(pupilUserId, classroomId, stopId, activeStops) } @@ -183,4 +184,4 @@ class PupilStopProgressService( ) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/PupilStopProgressServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/PupilStopProgressServiceTests.kt index 50bc07da..8a0481f6 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 @@ -243,6 +243,32 @@ class PupilStopProgressServiceTests { assertEquals(7L, result.currentTaskId) } + @Test + fun `update progress clears current task id when stop completes`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS).apply { + currentTaskId = 7L + } + + stubFindAndSave(progressRepository, record) + Mockito.`when`(mapStopRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()) + .thenReturn(listOf(MapStop().apply { id = 1L })) + + val result = service.updateProgress( + pupilUserId = 1L, classroomId = 2L, stopId = 1L, + command = UpdateStopProgressCommand( + status = StopProgressStatus.COMPLETED, + currentTaskId = null, + bestScore = null, + medalAwarded = null, + ), + ) + + assertNull(result.currentTaskId) + } + @Test fun `update progress awards medal when medal flag is set`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) @@ -314,4 +340,4 @@ class PupilStopProgressServiceTests { stubFind(repo, record) Mockito.`when`(repo.save(any(PupilStopProgress::class.java))).thenAnswer { it.arguments[0] } } -} \ No newline at end of file +} From fb2f57c55c98d6049de9eb17d31ddaa344c51a74 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 10:23:06 +0200 Subject: [PATCH 12/16] feedback empty =/= all correct --- .../game/tasks/application/TaskService.kt | 4 +- .../game/tasks/TaskApiIntegrationTests.kt | 92 +++++++++++++++++-- 2 files changed, 88 insertions(+), 8 deletions(-) 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 e4de305e..84fef763 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 @@ -556,6 +556,7 @@ class TaskService( val baseItemScore = if (task.items.isEmpty()) 0 else task.maxScore / task.items.size var score = 0 val feedback = mutableListOf() + var allAnswersCorrect = true task.items.forEach { item -> val itemId = requireNotNull(item.id) @@ -572,13 +573,14 @@ class TaskService( if (selectedOption.isCorrect) { score += baseItemScore } else { + allAnswersCorrect = false selectedOption.resolveExplanationText() .takeIf { it.nb != null || it.en != null } ?.let(feedback::add) } } - if (feedback.isEmpty()) { + if (allAnswersCorrect) { score = task.maxScore } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt index 4aa45ee0..4bb6e708 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt @@ -588,6 +588,72 @@ class TaskApiIntegrationTests { } } + @Test + fun `pupil wrong option without explanation still fails task`() { + val owner = userRepository.save(activeTeacher("owner@example.com")) + val classroom = createClassroom(owner, "TASK52") + val stop = createMapStop(slug = "bildekvartalet", title = "Image Quarter", displayOrder = 1) + val teacherAccessToken = teacherAccessToken("owner@example.com", "secret123") + + val createdBody = readJson( + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = optionTaskPayload(stopId = requireNotNull(stop.id), includeWrongExplanation = false) + }.andExpect { + status { isCreated() } + }.andReturn().response.contentAsString, + ) + val taskId = createdBody.get("id").asLong() + val taskItemId = createdBody.get("items")[0].get("id").asLong() + val wrongOptionId = createdBody.get("items")[0].get("options")[1].get("id").asLong() + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") + content = """{"published":true}""" + }.andExpect { + status { isOk() } + } + + val pupil = userRepository.save(activePupil("submitter_option_no_feedback")) + classroom.addPupilMembership(pupil) + classroomRepository.saveAndFlush(classroom) + createStopProgress(pupil, classroom, stop, StopProgressStatus.NOT_STARTED) + val pupilAccessToken = pupilAccessToken("submitter_option_no_feedback", "secret123") + + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks/submit-stop") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilAccessToken") + content = """ + { + "stopId": ${requireNotNull(stop.id)}, + "taskAnswers": [ + { + "taskId": $taskId, + "itemAnswers": [ + { + "itemId": $taskItemId, + "selectedOptionId": $wrongOptionId + } + ] + } + ] + } + """.trimIndent() + }.andExpect { + status { isOk() } + jsonPath("$.passed") { value(false) } + jsonPath("$.score") { value(0) } + jsonPath("$.stopStatus") { value("IN_PROGRESS") } + jsonPath("$.taskResults[0].passed") { value(false) } + jsonPath("$.taskResults[0].feedbackText") { doesNotExist() } + } + } + private fun createClassroom(owner: User, joinCode: String): Classroom = classroomRepository.save( Classroom( @@ -743,8 +809,23 @@ class TaskApiIntegrationTests { } """.trimIndent() - private fun optionTaskPayload(stopId: Long): String = - """ + private fun optionTaskPayload( + stopId: Long, + includeWrongExplanation: Boolean = true, + ): String { + val wrongExplanation = + if (includeWrongExplanation) { + """ + "explanationText": { + "nb":"Dette alternativet overser faresignalene i bildet.", + "en":"This option ignores the warning signs in the image." + } + """.trimIndent() + } else { + "" + } + + return """ { "stopId": $stopId, "title": {"nb":"Vurder bildet","en":"Assess the image"}, @@ -772,15 +853,12 @@ class TaskApiIntegrationTests { { "optionOrder": 2, "optionText": {"nb":"Bildet ser helt trygt ut.","en":"The image looks completely safe."}, - "isCorrect": false, - "explanationText": { - "nb":"Dette alternativet overser faresignalene i bildet.", - "en":"This option ignores the warning signs in the image." - } + "isCorrect": false${if (wrongExplanation.isNotBlank()) ",\n $wrongExplanation" else ""} } ] } ] } """.trimIndent() + } } From c4acb858533b6e08274441befd4c3e7822bf622e Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 10:42:25 +0200 Subject: [PATCH 13/16] use task options for news --- .../backend/bootstrap/DevDataBootstrap.kt | 141 +++++++++--------- .../backend/game/tasks/api/TaskApiMappings.kt | 3 - .../backend/game/tasks/api/TaskRequests.kt | 7 - .../backend/game/tasks/api/TaskResponses.kt | 3 - .../game/tasks/application/TaskModels.kt | 6 - .../game/tasks/application/TaskService.kt | 89 +---------- .../backend/game/tasks/domain/TaskItem.kt | 4 - .../game/tasks/domain/TaskItemTranslation.kt | 2 - .../V15__add_task_item_selection_feedback.sql | 8 - .../game/tasks/TaskApiIntegrationTests.kt | 87 +++++++---- 10 files changed, 129 insertions(+), 221 deletions(-) delete mode 100644 src/main/resources/db/migration/V15__add_task_item_selection_feedback.sql 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 edd543db..a88cd097 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 @@ -445,10 +445,8 @@ class DevDataBootstrap( promptText = itemSeed.promptText.nb, mediaUrl = itemSeed.mediaUrl, metadataJson = itemSeed.metadataJson, - isCorrectSelection = itemSeed.isCorrectSelection, - selectionExplanationText = itemSeed.selectionExplanationText?.nb, ) - addItemTranslations(item, itemSeed.promptText, itemSeed.selectionExplanationText) + addItemTranslations(item, itemSeed.promptText) itemSeed.options.forEach { optionSeed -> val option = TaskOption( optionOrder = optionSeed.optionOrder, @@ -489,14 +487,12 @@ class DevDataBootstrap( private fun addItemTranslations( item: TaskItem, promptText: LocalizedText, - selectionExplanationText: LocalizedOptionalText?, ) { item.addTranslation( TaskItemTranslation( id = TaskItemTranslationId(locale = TaskLocale.NB), locale = TaskLocale.NB, promptText = promptText.nb, - selectionExplanationText = selectionExplanationText?.nb, ), ) item.addTranslation( @@ -504,7 +500,6 @@ class DevDataBootstrap( id = TaskItemTranslationId(locale = TaskLocale.EN), locale = TaskLocale.EN, promptText = promptText.en, - selectionExplanationText = selectionExplanationText?.en, ), ) } @@ -546,30 +541,33 @@ class DevDataBootstrap( SeedItem( itemOrder = 1, promptText = localized( - "HELT UTROLIG! Forskning beviser at sjokolade er sunt!\n\nEn ny, banebrekkende studie har ENDELIG bevist det vi alle har håpet på: sjokolade er like sunt som – eller kanskje til og med sunnere enn – grønnsaker! Legen som ledet forskningen ble selv overrasket over resultatene.\n\n\"Vi kan ikke tro det vi ser. Sjokolade kurerer nesten alt,\" skal en navnløs forsker ha sagt.\n\nEksperter fra hele verden er nå i sjokk. Det anbefales å spise minst 200 gram sjokolade daglig for å holde seg frisk. Grønnsaker kan trygt droppes!\nDel denne artikkelen med alle du kjenner FØR myndighetene sensurerer den – Big Pharma vil ikke at du skal vite dette!", - "UNBELIEVABLE! Research proves chocolate is healthy!\n\nA groundbreaking new study has FINALLY proven what we all hoped: chocolate is just as healthy as - or perhaps even healthier than - vegetables! The doctor who led the research was surprised by the results.\n\n\"We cannot believe what we are seeing. Chocolate cures almost everything,\" an anonymous researcher allegedly said.\n\nExperts worldwide are now in shock. It is recommended to eat at least 200 grams of chocolate daily to stay healthy. Vegetables can safely be dropped!\nShare this article with everyone you know BEFORE the authorities censor it - Big Pharma does not want you to know this!", + "Hvilken artikkel virker mest troverdig?", + "Which article appears most trustworthy?", ), - metadataJson = """{"domain":"helserevolusjonen.no"}""", - selectionExplanationText = localizedOptional( - "Denne saken bruker sensasjonelt språk, anonyme kilder og overdrevne påstander uten troverdige bevis.", - "This story uses sensational language, anonymous sources, and exaggerated claims without credible evidence.", + metadataJson = """ + {"articles":[ + {"optionOrder":1,"domain":"helserevolusjonen.no","mediaUrl":null}, + {"optionOrder":2,"domain":"forskning.no","mediaUrl":"https://images.unsplash.com/photo-1481391319762-47dff72954d9?w=600&q=80"} + ]} + """.trimIndent(), + options = listOf( + explainedOption( + 1, + "HELT UTROLIG! Forskning beviser at sjokolade er sunt!\n\nEn ny, banebrekkende studie har ENDELIG bevist det vi alle har håpet på: sjokolade er like sunt som – eller kanskje til og med sunnere enn – grønnsaker! Legen som ledet forskningen ble selv overrasket over resultatene.\n\n\"Vi kan ikke tro det vi ser. Sjokolade kurerer nesten alt,\" skal en navnløs forsker ha sagt.\n\nEksperter fra hele verden er nå i sjokk. Det anbefales å spise minst 200 gram sjokolade daglig for å holde seg frisk. Grønnsaker kan trygt droppes!\nDel denne artikkelen med alle du kjenner FØR myndighetene sensurerer den – Big Pharma vil ikke at du skal vite dette!", + "UNBELIEVABLE! Research proves chocolate is healthy!\n\nA groundbreaking new study has FINALLY proven what we all hoped: chocolate is just as healthy as - or perhaps even healthier than - vegetables! The doctor who led the research was surprised by the results.\n\n\"We cannot believe what we are seeing. Chocolate cures almost everything,\" an anonymous researcher allegedly said.\n\nExperts worldwide are now in shock. It is recommended to eat at least 200 grams of chocolate daily to stay healthy. Vegetables can safely be dropped!\nShare this article with everyone you know BEFORE the authorities censor it - Big Pharma does not want you to know this!", + false, + "Denne saken bruker sensasjonelt språk, anonyme kilder og overdrevne påstander uten troverdige bevis.", + "This story uses sensational language, anonymous sources, and exaggerated claims without credible evidence.", + ), + explainedOption( + 2, + "Studie: Mørk sjokolade kan ha helsegevinster\n\nEn ny studie publisert i tidsskriftet Nutrients viser at flavonoider i mørk sjokolade (70 % kakao eller mer) kan bidra til lavere blodtrykk og bedre insulinfølsomhet hos noen voksne.\n\n\"Effekten er reell, men begrenset. Dette er ikke en erstatning for et sunt kosthold med grønnsaker, frukt og fiber,\" sier ernæringsforsker Tone Berg ved UiO.\n\nStudien fulgte 200 deltakere over 12 uker og målte blodtrykk og betennelsesmarkører. Forskerne understreker at porsjonsstørrelse er avgjørende – rundt 20–30 gram per dag var mengden brukt i forsøket. Helsedirektoratet minner om at sjokolade fortsatt er kaloririk og ikke inngår i de generelle kostrådene.", + "Study: Dark chocolate may have health benefits\n\nA new study published in the journal Nutrients shows that flavonoids in dark chocolate (70% cocoa or more) may contribute to lower blood pressure and better insulin sensitivity in some adults.\n\n\"The effect is real but limited. This is not a replacement for a healthy diet with vegetables, fruit, and fibre,\" says nutritional researcher Tone Berg at UiO.\n\nThe study followed 200 participants over 12 weeks and measured blood pressure and inflammation markers. Researchers emphasise that portion size is decisive - around 20-30 grams per day was the amount used in the trial. The Directorate of Health notes that chocolate remains calorie-dense and is not part of general dietary guidelines.", + true, + "Denne saken viser til en konkret studie, oppgir kilde og forklarer begrensningene i funnene.", + "This story cites a concrete study, names the source, and explains the limits of the findings.", + ), ), - options = emptyList(), - ), - SeedItem( - itemOrder = 2, - promptText = localized( - "Studie: Mørk sjokolade kan ha helsegevinster\n\nEn ny studie publisert i tidsskriftet Nutrients viser at flavonoider i mørk sjokolade (70 % kakao eller mer) kan bidra til lavere blodtrykk og bedre insulinfølsomhet hos noen voksne.\n\n\"Effekten er reell, men begrenset. Dette er ikke en erstatning for et sunt kosthold med grønnsaker, frukt og fiber,\" sier ernæringsforsker Tone Berg ved UiO.\n\nStudien fulgte 200 deltakere over 12 uker og målte blodtrykk og betennelsesmarkører. Forskerne understreker at porsjonsstørrelse er avgjørende – rundt 20–30 gram per dag var mengden brukt i forsøket. Helsedirektoratet minner om at sjokolade fortsatt er kaloririk og ikke inngår i de generelle kostrådene.", - "Study: Dark chocolate may have health benefits\n\nA new study published in the journal Nutrients shows that flavonoids in dark chocolate (70% cocoa or more) may contribute to lower blood pressure and better insulin sensitivity in some adults.\n\n\"The effect is real but limited. This is not a replacement for a healthy diet with vegetables, fruit, and fibre,\" says nutritional researcher Tone Berg at UiO.\n\nThe study followed 200 participants over 12 weeks and measured blood pressure and inflammation markers. Researchers emphasise that portion size is decisive - around 20-30 grams per day was the amount used in the trial. The Directorate of Health notes that chocolate remains calorie-dense and is not part of general dietary guidelines.", - ), - mediaUrl = "https://images.unsplash.com/photo-1481391319762-47dff72954d9?w=600&q=80", - metadataJson = """{"domain":"forskning.no"}""", - isCorrectSelection = true, - selectionExplanationText = localizedOptional( - "Denne saken viser til en konkret studie, oppgir kilde og forklarer begrensningene i funnene.", - "This story cites a concrete study, names the source, and explains the limits of the findings.", - ), - options = emptyList(), ), ), ), @@ -585,29 +583,33 @@ class DevDataBootstrap( SeedItem( itemOrder = 1, promptText = localized( - "LEGEN HAR IKKE FORTALT DEG DETTE! Én enkel ting kurerer alle sykdommer\n\nLegemiddelindustrien skjuler en hemmelighet som kan endre livet ditt. En ukjent doktor avslørte nylig at du ALDRI trenger å bli syk igjen. Klikk her for å finne ut hva Big Pharma ikke vil du skal vite.", - "YOUR DOCTOR NEVER TOLD YOU THIS! One simple thing cures all diseases\n\nThe pharmaceutical industry is hiding a secret that could change your life. An unknown doctor recently revealed you NEVER have to get sick again. Click here to find out what Big Pharma does not want you to know.", - ), - metadataJson = """{"domain":"helseavsloringer.net"}""", - selectionExplanationText = localizedOptional( - "Denne saken bruker clickbait, sterke følelsesord og udokumenterte påstander for å lokke deg til å klikke.", - "This story uses clickbait, emotional language, and unsupported claims to make you click.", - ), - options = emptyList(), - ), - SeedItem( - itemOrder = 2, - promptText = localized( - "Ny rapport: Regelmessig mosjon reduserer risiko for hjerte- og karsykdommer\n\nFolkehelseinstituttet presenterte i dag en ny rapport som viser at 150 minutter moderat fysisk aktivitet per uke er forbundet med 35 prosent lavere risiko for hjerteinfarkt hos voksne over 40 år. Rapporten bygger på data fra over 50 000 nordmenn fulgt over ti år.", - "New report: Regular exercise reduces risk of cardiovascular disease\n\nThe Norwegian Institute of Public Health today presented a new report showing that 150 minutes of moderate physical activity per week is associated with a 35 percent lower risk of heart attack in adults over 40. The report is based on data from over 50,000 Norwegians followed over ten years.", + "Hvilken artikkel bruker mest seriøst og nøytralt språk?", + "Which article uses the most serious and neutral language?", ), - metadataJson = """{"domain":"fhi.no"}""", - isCorrectSelection = true, - selectionExplanationText = localizedOptional( - "Denne saken bruker nøkternt språk, oppgir avsender og beskriver datagrunnlaget på en etterprøvbar måte.", - "This story uses neutral language, names the source, and describes the evidence in a verifiable way.", + metadataJson = """ + {"articles":[ + {"optionOrder":1,"domain":"helseavsloringer.net","mediaUrl":null}, + {"optionOrder":2,"domain":"fhi.no","mediaUrl":null} + ]} + """.trimIndent(), + options = listOf( + explainedOption( + 1, + "LEGEN HAR IKKE FORTALT DEG DETTE! Én enkel ting kurerer alle sykdommer\n\nLegemiddelindustrien skjuler en hemmelighet som kan endre livet ditt. En ukjent doktor avslørte nylig at du ALDRI trenger å bli syk igjen. Klikk her for å finne ut hva Big Pharma ikke vil du skal vite.", + "YOUR DOCTOR NEVER TOLD YOU THIS! One simple thing cures all diseases\n\nThe pharmaceutical industry is hiding a secret that could change your life. An unknown doctor recently revealed you NEVER have to get sick again. Click here to find out what Big Pharma does not want you to know.", + false, + "Denne saken bruker clickbait, sterke følelsesord og udokumenterte påstander for å lokke deg til å klikke.", + "This story uses clickbait, emotional language, and unsupported claims to make you click.", + ), + explainedOption( + 2, + "Ny rapport: Regelmessig mosjon reduserer risiko for hjerte- og karsykdommer\n\nFolkehelseinstituttet presenterte i dag en ny rapport som viser at 150 minutter moderat fysisk aktivitet per uke er forbundet med 35 prosent lavere risiko for hjerteinfarkt hos voksne over 40 år. Rapporten bygger på data fra over 50 000 nordmenn fulgt over ti år.", + "New report: Regular exercise reduces risk of cardiovascular disease\n\nThe Norwegian Institute of Public Health today presented a new report showing that 150 minutes of moderate physical activity per week is associated with a 35 percent lower risk of heart attack in adults over 40. The report is based on data from over 50,000 Norwegians followed over ten years.", + true, + "Denne saken bruker nøkternt språk, oppgir avsender og beskriver datagrunnlaget på en etterprøvbar måte.", + "This story uses neutral language, names the source, and describes the evidence in a verifiable way.", + ), ), - options = emptyList(), ), ), ), @@ -623,29 +625,28 @@ class DevDataBootstrap( SeedItem( itemOrder = 1, promptText = localized( - "Tre klasser testet lesetidene sine i to uker og skrev ned resultatene.", - "Three classes tested their reading times for two weeks and wrote down the results.", - ), - metadataJson = null, - isCorrectSelection = true, - selectionExplanationText = localizedOptional( - "Denne teksten beskriver observerbare fakta uten å presse fram en følelsesmessig reaksjon.", - "This text describes observable facts without trying to force an emotional reaction.", - ), - options = emptyList(), - ), - SeedItem( - itemOrder = 2, - promptText = localized( - "Alle er rasende etter den utrolig skumle nyheten som sprer seg overalt.", - "Everyone is furious after the incredibly scary news spreading everywhere.", + "Hvilken tekst bruker mest fakta og minst følelsespress?", + "Which text uses the most facts and the least emotional pressure?", ), metadataJson = null, - selectionExplanationText = localizedOptional( - "Denne teksten bruker følelsesladde ord som 'rasende' og 'skumle' i stedet for konkrete fakta.", - "This text uses emotional words like 'furious' and 'scary' instead of concrete facts.", + options = listOf( + explainedOption( + 1, + "Tre klasser testet lesetidene sine i to uker og skrev ned resultatene.", + "Three classes tested their reading times for two weeks and wrote down the results.", + true, + "Denne teksten beskriver observerbare fakta uten å presse fram en følelsesmessig reaksjon.", + "This text describes observable facts without trying to force an emotional reaction.", + ), + explainedOption( + 2, + "Alle er rasende etter den utrolig skumle nyheten som sprer seg overalt.", + "Everyone is furious after the incredibly scary news spreading everywhere.", + false, + "Denne teksten bruker følelsesladde ord som 'rasende' og 'skumle' i stedet for konkrete fakta.", + "This text uses emotional words like 'furious' and 'scary' instead of concrete facts.", + ), ), - options = emptyList(), ), ), ), @@ -1308,8 +1309,6 @@ class DevDataBootstrap( val promptText: LocalizedText, val mediaUrl: String? = null, val metadataJson: String? = null, - val isCorrectSelection: Boolean = false, - val selectionExplanationText: LocalizedOptionalText? = null, val options: List, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt index bc17cf1f..428a2498 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt @@ -52,8 +52,6 @@ fun TaskDetails.toResponse(includeAnswers: Boolean = true): TaskResponse = promptText = item.promptText.toResponse(), mediaUrl = item.mediaUrl, metadataJson = item.metadataJson, - isCorrectSelection = item.isCorrectSelection.takeIf { includeAnswers }, - selectionExplanationText = item.selectionExplanationText?.takeIf { includeAnswers }?.toResponse(), options = item.options.map { option -> TaskOptionResponse( id = option.id, @@ -91,6 +89,5 @@ private fun TaskSubmissionResult.toResponse(): TaskSubmissionResultResponse = passed = passed, score = score, maxScore = maxScore, - selectedItemId = selectedItemId, feedbackText = feedbackText?.toResponse(), ) 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 255257c3..d5dd07d0 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 @@ -57,9 +57,6 @@ data class TaskItemRequest( var promptText: LocalizedRequiredTextRequest, val mediaUrl: String? = null, val metadataJson: String? = null, - val isCorrectSelection: Boolean = false, - @field:Valid - val selectionExplanationText: LocalizedOptionalTextRequest? = null, @field:Valid val options: List = emptyList(), ) @@ -74,7 +71,6 @@ data class SubmitStopAnswersRequest( data class SubmitTaskAnswerRequest( @field:Min(1) val taskId: Long, - val selectedItemId: Long? = null, @field:Valid val itemAnswers: List = emptyList(), ) @@ -194,8 +190,6 @@ private fun List.toCommands(): List = promptText = item.promptText.toLocalizedText(), mediaUrl = item.mediaUrl, metadataJson = item.metadataJson, - isCorrectSelection = item.isCorrectSelection, - selectionExplanationText = item.selectionExplanationText?.toLocalizedOptionalText(), options = item.options.map { option -> ReplaceTaskOptionCommand( optionOrder = option.optionOrder, @@ -223,7 +217,6 @@ fun SubmitStopAnswersRequest.toCommand( taskAnswers = taskAnswers.map { taskAnswer -> edu.ntnu.idi.idatt.backend.game.tasks.application.SubmitTaskAnswerCommand( taskId = taskAnswer.taskId, - selectedItemId = taskAnswer.selectedItemId, itemAnswers = taskAnswer.itemAnswers.map { itemAnswer -> edu.ntnu.idi.idatt.backend.game.tasks.application.SubmitItemAnswerCommand( itemId = itemAnswer.itemId, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt index fd60b941..28bf8abc 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt @@ -43,8 +43,6 @@ data class TaskItemResponse( val promptText: LocalizedTextResponse, val mediaUrl: String?, val metadataJson: String?, - val isCorrectSelection: Boolean?, - val selectionExplanationText: LocalizedOptionalTextResponse?, val options: List, ) @@ -90,7 +88,6 @@ data class TaskSubmissionResultResponse( val passed: Boolean, val score: Int, val maxScore: Int, - val selectedItemId: Long?, val feedbackText: LocalizedOptionalTextResponse?, ) 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 729ae899..5e92f752 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 @@ -38,8 +38,6 @@ data class ReplaceTaskItemCommand( val promptText: LocalizedText, val mediaUrl: String?, val metadataJson: String?, - val isCorrectSelection: Boolean, - val selectionExplanationText: LocalizedOptionalText?, val options: List, ) @@ -98,8 +96,6 @@ data class TaskItemDetails( val promptText: LocalizedText, val mediaUrl: String?, val metadataJson: String?, - val isCorrectSelection: Boolean, - val selectionExplanationText: LocalizedOptionalText?, val options: List, ) @@ -156,7 +152,6 @@ data class SubmitStopAnswersCommand( data class SubmitTaskAnswerCommand( val taskId: Long, - val selectedItemId: Long?, val itemAnswers: List, ) @@ -181,6 +176,5 @@ data class TaskSubmissionResult( val passed: Boolean, val score: Int, val maxScore: Int, - val selectedItemId: Long?, val feedbackText: LocalizedOptionalText?, ) 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 84fef763..9dddaf88 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 @@ -319,10 +319,8 @@ class TaskService( promptText = itemCommand.promptText.nb.trim(), mediaUrl = itemCommand.mediaUrl?.trim()?.takeIf { it.isNotBlank() }, metadataJson = itemCommand.metadataJson?.trim()?.takeIf { it.isNotBlank() }, - isCorrectSelection = itemCommand.isCorrectSelection, - selectionExplanationText = itemCommand.selectionExplanationText?.nb?.trim()?.takeIf { it.isNotBlank() }, ) - replaceItemTranslations(item, itemCommand.promptText, itemCommand.selectionExplanationText) + replaceItemTranslations(item, itemCommand.promptText) itemCommand.options.sortedBy { it.optionOrder }.forEach { optionCommand -> val option = TaskOption( optionOrder = optionCommand.optionOrder, @@ -340,7 +338,6 @@ class TaskService( private fun replaceItemTranslations( item: TaskItem, promptText: LocalizedText, - selectionExplanationText: LocalizedOptionalText?, ) { item.translations.clear() item.addTranslation( @@ -348,7 +345,6 @@ class TaskService( id = TaskItemTranslationId(locale = TaskLocale.NB), locale = TaskLocale.NB, promptText = promptText.nb.trim(), - selectionExplanationText = selectionExplanationText?.nb?.trim()?.takeIf { it.isNotBlank() }, ), ) item.addTranslation( @@ -356,7 +352,6 @@ class TaskService( id = TaskItemTranslationId(locale = TaskLocale.EN), locale = TaskLocale.EN, promptText = promptText.en.trim(), - selectionExplanationText = selectionExplanationText?.en?.trim()?.takeIf { it.isNotBlank() }, ), ) } @@ -446,23 +441,6 @@ class TaskService( throw ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Published tasks must include at least one item") } - val itemSelectionMode = task.items.all { it.options.isEmpty() } - if (itemSelectionMode) { - if (task.items.size < 2) { - throw ResponseStatusException( - HttpStatus.UNPROCESSABLE_ENTITY, - "Item-selection tasks must include at least two items", - ) - } - if (task.items.count { it.isCorrectSelection } != 1) { - throw ResponseStatusException( - HttpStatus.UNPROCESSABLE_ENTITY, - "Item-selection tasks must mark exactly one item as correct", - ) - } - return - } - task.items.forEach { item -> if (item.options.size < 2) { throw ResponseStatusException( @@ -483,66 +461,12 @@ class TaskService( task: Task, taskAnswer: SubmitTaskAnswerCommand, ): TaskSubmissionResult = - if (task.items.all { it.options.isEmpty() }) { - evaluateItemSelectionTask(task, taskAnswer) - } else { - evaluateOptionBasedTask(task, taskAnswer) - } - - private fun evaluateItemSelectionTask( - task: Task, - taskAnswer: SubmitTaskAnswerCommand, - ): TaskSubmissionResult { - if (taskAnswer.itemAnswers.isNotEmpty()) { - throw ResponseStatusException( - HttpStatus.BAD_REQUEST, - "Task ${requireNotNull(task.id)} expects selectedItemId, not per-item option answers", - ) - } - - val selectedItemId = taskAnswer.selectedItemId - ?: throw ResponseStatusException( - HttpStatus.BAD_REQUEST, - "Task ${requireNotNull(task.id)} is missing selectedItemId", - ) - val selectedItem = task.items.firstOrNull { it.id == selectedItemId } - ?: throw ResponseStatusException( - HttpStatus.BAD_REQUEST, - "Selected item $selectedItemId does not belong to task ${requireNotNull(task.id)}", - ) - - if (task.items.count { it.isCorrectSelection } != 1) { - throw ResponseStatusException( - HttpStatus.UNPROCESSABLE_ENTITY, - "Task ${requireNotNull(task.id)} is not configured with exactly one correct item", - ) - } - - val score = if (selectedItem.isCorrectSelection) task.maxScore else 0 - return TaskSubmissionResult( - taskId = requireNotNull(task.id), - title = task.resolveTitle(), - passed = passesTask(task, score), - score = score, - maxScore = task.maxScore, - selectedItemId = selectedItemId, - feedbackText = selectedItem.resolveSelectionExplanationText().takeIf { - it.nb != null || it.en != null - }, - ) - } + evaluateOptionBasedTask(task, taskAnswer) private fun evaluateOptionBasedTask( task: Task, taskAnswer: SubmitTaskAnswerCommand, ): TaskSubmissionResult { - if (taskAnswer.selectedItemId != null) { - throw ResponseStatusException( - HttpStatus.BAD_REQUEST, - "Task ${requireNotNull(task.id)} expects per-item option answers, not selectedItemId", - ) - } - val answerByItemId = taskAnswer.itemAnswers.associateBy { it.itemId } val expectedItemIds = task.items.mapNotNull { it.id }.toSet() val unexpectedItemIds = answerByItemId.keys - expectedItemIds @@ -590,7 +514,6 @@ class TaskService( passed = passesTask(task, score), score = score, maxScore = task.maxScore, - selectedItemId = null, feedbackText = combineFeedback(feedback), ) } @@ -751,8 +674,6 @@ private fun Task.toDetails(): TaskDetails = promptText = item.resolvePromptText(), mediaUrl = item.mediaUrl, metadataJson = item.metadataJson, - isCorrectSelection = item.isCorrectSelection, - selectionExplanationText = item.resolveSelectionExplanationText(), options = item.options.sortedBy { it.optionOrder }.map { option -> TaskOptionDetails( id = requireNotNull(option.id), @@ -784,12 +705,6 @@ private fun TaskItem.resolvePromptText(): LocalizedText = en = translations.firstOrNull { it.locale == TaskLocale.EN }?.promptText ?: promptText, ) -private fun TaskItem.resolveSelectionExplanationText(): LocalizedOptionalText = - LocalizedOptionalText( - nb = translations.firstOrNull { it.locale == TaskLocale.NB }?.selectionExplanationText ?: selectionExplanationText, - en = translations.firstOrNull { it.locale == TaskLocale.EN }?.selectionExplanationText ?: selectionExplanationText, - ) - private fun TaskOption.resolveOptionText(): LocalizedText = LocalizedText( nb = translations.firstOrNull { it.locale == TaskLocale.NB }?.optionText ?: optionText, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt index 3ef8ad9c..8b884df0 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItem.kt @@ -33,10 +33,6 @@ class TaskItem( var mediaUrl: String? = null, @Column(name = "metadata_json") var metadataJson: String? = null, - @Column(name = "is_correct_selection", nullable = false) - var isCorrectSelection: Boolean = false, - @Column(name = "selection_explanation_text") - var selectionExplanationText: String? = null, @OneToMany( mappedBy = "taskItem", cascade = [CascadeType.ALL], diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt index b942bbda..48e4a78e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/domain/TaskItemTranslation.kt @@ -30,8 +30,6 @@ class TaskItemTranslation( var locale: TaskLocale = TaskLocale.NB, @Column(name = "prompt_text", nullable = false) var promptText: String = "", - @Column(name = "selection_explanation_text") - var selectionExplanationText: String? = null, ) /** diff --git a/src/main/resources/db/migration/V15__add_task_item_selection_feedback.sql b/src/main/resources/db/migration/V15__add_task_item_selection_feedback.sql deleted file mode 100644 index f7976df6..00000000 --- a/src/main/resources/db/migration/V15__add_task_item_selection_feedback.sql +++ /dev/null @@ -1,8 +0,0 @@ -ALTER TABLE task_items - ADD COLUMN is_correct_selection BOOLEAN NOT NULL DEFAULT FALSE; - -ALTER TABLE task_items - ADD COLUMN selection_explanation_text TEXT; - -ALTER TABLE task_item_translations - ADD COLUMN selection_explanation_text TEXT; diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt index 4bb6e708..356143a8 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt @@ -340,13 +340,14 @@ class TaskApiIntegrationTests { with(csrf()) contentType = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") - content = itemSelectionTaskPayload(stopId = requireNotNull(stop.id)) + content = newsComparisonTaskPayload(stopId = requireNotNull(stop.id)) }.andExpect { status { isCreated() } }.andReturn().response.contentAsString, ) val taskId = createdBody.get("id").asLong() - val wrongItemId = createdBody.get("items")[0].get("id").asLong() + val taskItemId = createdBody.get("items")[0].get("id").asLong() + val wrongOptionId = createdBody.get("items")[0].get("options")[0].get("id").asLong() mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { with(csrf()) @@ -373,7 +374,12 @@ class TaskApiIntegrationTests { "taskAnswers": [ { "taskId": $taskId, - "selectedItemId": $wrongItemId + "itemAnswers": [ + { + "itemId": $taskItemId, + "selectedOptionId": $wrongOptionId + } + ] } ] } @@ -383,7 +389,6 @@ class TaskApiIntegrationTests { jsonPath("$.passed") { value(false) } jsonPath("$.stopStatus") { value("IN_PROGRESS") } jsonPath("$.taskResults[0].passed") { value(false) } - jsonPath("$.taskResults[0].selectedItemId") { value(wrongItemId) } jsonPath("$.taskResults[0].feedbackText.en") { value("This article uses sensational language and makes unsupported claims.") } @@ -410,13 +415,14 @@ class TaskApiIntegrationTests { with(csrf()) contentType = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") - content = itemSelectionTaskPayload(stopId = requireNotNull(stop.id)) + content = newsComparisonTaskPayload(stopId = requireNotNull(stop.id)) }.andExpect { status { isCreated() } }.andReturn().response.contentAsString, ) val taskId = createdBody.get("id").asLong() - val correctItemId = createdBody.get("items")[1].get("id").asLong() + val taskItemId = createdBody.get("items")[0].get("id").asLong() + val correctOptionId = createdBody.get("items")[0].get("options")[1].get("id").asLong() mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { with(csrf()) @@ -443,7 +449,12 @@ class TaskApiIntegrationTests { "taskAnswers": [ { "taskId": $taskId, - "selectedItemId": $correctItemId + "itemAnswers": [ + { + "itemId": $taskItemId, + "selectedOptionId": $correctOptionId + } + ] } ] } @@ -464,6 +475,7 @@ class TaskApiIntegrationTests { assertEquals(StopProgressStatus.COMPLETED, progress?.status) assertEquals(100, progress?.bestScore) assertEquals(true, progress?.medalAwarded) + assertEquals(null, progress?.currentTaskId) } @Test @@ -478,13 +490,14 @@ class TaskApiIntegrationTests { with(csrf()) contentType = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, "Bearer $teacherAccessToken") - content = itemSelectionTaskPayload(stopId = requireNotNull(stop.id)) + content = newsComparisonTaskPayload(stopId = requireNotNull(stop.id)) }.andExpect { status { isCreated() } }.andReturn().response.contentAsString, ) val taskId = createdBody.get("id").asLong() - val correctItemId = createdBody.get("items")[1].get("id").asLong() + val taskItemId = createdBody.get("items")[0].get("id").asLong() + val correctOptionId = createdBody.get("items")[0].get("options")[1].get("id").asLong() mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { with(csrf()) @@ -511,7 +524,12 @@ class TaskApiIntegrationTests { "taskAnswers": [ { "taskId": $taskId, - "selectedItemId": $correctItemId + "itemAnswers": [ + { + "itemId": $taskItemId, + "selectedOptionId": $correctOptionId + } + ] } ] } @@ -771,7 +789,7 @@ class TaskApiIntegrationTests { } """.trimIndent() - private fun itemSelectionTaskPayload(stopId: Long): String = + private fun newsComparisonTaskPayload(stopId: Long): String = """ { "stopId": $stopId, @@ -785,25 +803,34 @@ class TaskApiIntegrationTests { "items": [ { "itemOrder": 1, - "promptText": {"nb":"Sensasjonell artikkel","en":"Sensational article"}, - "metadataJson": "{\"domain\":\"clickbait.example\"}", - "isCorrectSelection": false, - "selectionExplanationText": { - "nb":"Denne artikkelen bruker sensasjonelt språk og udokumenterte påstander.", - "en":"This article uses sensational language and makes unsupported claims." - }, - "options": [] - }, - { - "itemOrder": 2, - "promptText": {"nb":"Nøktern artikkel","en":"Measured article"}, - "metadataJson": "{\"domain\":\"news.example\"}", - "isCorrectSelection": true, - "selectionExplanationText": { - "nb":"Denne artikkelen oppgir kilde og forklarer fakta på en etterprøvbar måte.", - "en":"This article names its source and explains the facts in a verifiable way." - }, - "options": [] + "promptText": {"nb":"Hvilken artikkel er mest troverdig?","en":"Which article is most trustworthy?"}, + "metadataJson": "{\"articles\":[{\"optionOrder\":1,\"domain\":\"clickbait.example\",\"mediaUrl\":null},{\"optionOrder\":2,\"domain\":\"news.example\",\"mediaUrl\":null}]}", + "options": [ + { + "optionOrder": 1, + "optionText": { + "nb":"Sensasjonell artikkel", + "en":"Sensational article" + }, + "isCorrect": false, + "explanationText": { + "nb":"Denne artikkelen bruker sensasjonelt språk og udokumenterte påstander.", + "en":"This article uses sensational language and makes unsupported claims." + } + }, + { + "optionOrder": 2, + "optionText": { + "nb":"Nøktern artikkel", + "en":"Measured article" + }, + "isCorrect": true, + "explanationText": { + "nb":"Denne artikkelen oppgir kilde og forklarer fakta på en etterprøvbar måte.", + "en":"This article names its source and explains the facts in a verifiable way." + } + } + ] } ] } From 46f57ac5e6b37e11f27268173f7918dfa09de7a9 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 10:53:30 +0200 Subject: [PATCH 14/16] add headline to news metadata json --- .../backend/bootstrap/DevDataBootstrap.kt | 15 +++++--- .../game/tasks/TaskApiIntegrationTests.kt | 38 ++++++++++++++++++- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt index a88cd097..16e8fe0c 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 @@ -546,8 +546,8 @@ class DevDataBootstrap( ), metadataJson = """ {"articles":[ - {"optionOrder":1,"domain":"helserevolusjonen.no","mediaUrl":null}, - {"optionOrder":2,"domain":"forskning.no","mediaUrl":"https://images.unsplash.com/photo-1481391319762-47dff72954d9?w=600&q=80"} + {"optionOrder":1,"domain":"helserevolusjonen.no","headline":{"nb":"HELT UTROLIG! Forskning beviser at sjokolade er sunt!","en":"UNBELIEVABLE! Research proves chocolate is healthy!"},"body":{"nb":"En ny, banebrekkende studie har ENDELIG bevist det vi alle har håpet på: sjokolade er like sunt som – eller kanskje til og med sunnere enn – grønnsaker! Legen som ledet forskningen ble selv overrasket over resultatene.\n\n\"Vi kan ikke tro det vi ser. Sjokolade kurerer nesten alt,\" skal en navnløs forsker ha sagt.\n\nEksperter fra hele verden er nå i sjokk. Det anbefales å spise minst 200 gram sjokolade daglig for å holde seg frisk. Grønnsaker kan trygt droppes!\nDel denne artikkelen med alle du kjenner FØR myndighetene sensurerer den – Big Pharma vil ikke at du skal vite dette!","en":"A groundbreaking new study has FINALLY proven what we all hoped: chocolate is just as healthy as - or perhaps even healthier than - vegetables! The doctor who led the research was surprised by the results.\n\n\"We cannot believe what we are seeing. Chocolate cures almost everything,\" an anonymous researcher allegedly said.\n\nExperts worldwide are now in shock. It is recommended to eat at least 200 grams of chocolate daily to stay healthy. Vegetables can safely be dropped!\nShare this article with everyone you know BEFORE the authorities censor it - Big Pharma does not want you to know this!"},"mediaUrl":null}, + {"optionOrder":2,"domain":"forskning.no","headline":{"nb":"Studie: Mørk sjokolade kan ha helsegevinster","en":"Study: Dark chocolate may have health benefits"},"body":{"nb":"En ny studie publisert i tidsskriftet Nutrients viser at flavonoider i mørk sjokolade (70 % kakao eller mer) kan bidra til lavere blodtrykk og bedre insulinfølsomhet hos noen voksne.\n\n\"Effekten er reell, men begrenset. Dette er ikke en erstatning for et sunt kosthold med grønnsaker, frukt og fiber,\" sier ernæringsforsker Tone Berg ved UiO.\n\nStudien fulgte 200 deltakere over 12 uker og målte blodtrykk og betennelsesmarkører. Forskerne understreker at porsjonsstørrelse er avgjørende – rundt 20–30 gram per dag var mengden brukt i forsøket. Helsedirektoratet minner om at sjokolade fortsatt er kaloririk og ikke inngår i de generelle kostrådene.","en":"A new study published in the journal Nutrients shows that flavonoids in dark chocolate (70% cocoa or more) may contribute to lower blood pressure and better insulin sensitivity in some adults.\n\n\"The effect is real but limited. This is not a replacement for a healthy diet with vegetables, fruit, and fibre,\" says nutritional researcher Tone Berg at UiO.\n\nThe study followed 200 participants over 12 weeks and measured blood pressure and inflammation markers. Researchers emphasise that portion size is decisive - around 20-30 grams per day was the amount used in the trial. The Directorate of Health notes that chocolate remains calorie-dense and is not part of general dietary guidelines."},"mediaUrl":"https://images.unsplash.com/photo-1481391319762-47dff72954d9?w=600&q=80"} ]} """.trimIndent(), options = listOf( @@ -588,8 +588,8 @@ class DevDataBootstrap( ), metadataJson = """ {"articles":[ - {"optionOrder":1,"domain":"helseavsloringer.net","mediaUrl":null}, - {"optionOrder":2,"domain":"fhi.no","mediaUrl":null} + {"optionOrder":1,"domain":"helseavsloringer.net","headline":{"nb":"LEGEN HAR IKKE FORTALT DEG DETTE! Én enkel ting kurerer alle sykdommer","en":"YOUR DOCTOR NEVER TOLD YOU THIS! One simple thing cures all diseases"},"body":{"nb":"Legemiddelindustrien skjuler en hemmelighet som kan endre livet ditt. En ukjent doktor avslørte nylig at du ALDRI trenger å bli syk igjen. Klikk her for å finne ut hva Big Pharma ikke vil du skal vite.","en":"The pharmaceutical industry is hiding a secret that could change your life. An unknown doctor recently revealed you NEVER have to get sick again. Click here to find out what Big Pharma does not want you to know."},"mediaUrl":null}, + {"optionOrder":2,"domain":"fhi.no","headline":{"nb":"Ny rapport: Regelmessig mosjon reduserer risiko for hjerte- og karsykdommer","en":"New report: Regular exercise reduces risk of cardiovascular disease"},"body":{"nb":"Folkehelseinstituttet presenterte i dag en ny rapport som viser at 150 minutter moderat fysisk aktivitet per uke er forbundet med 35 prosent lavere risiko for hjerteinfarkt hos voksne over 40 år. Rapporten bygger på data fra over 50 000 nordmenn fulgt over ti år.","en":"The Norwegian Institute of Public Health today presented a new report showing that 150 minutes of moderate physical activity per week is associated with a 35 percent lower risk of heart attack in adults over 40. The report is based on data from over 50,000 Norwegians followed over ten years."},"mediaUrl":null} ]} """.trimIndent(), options = listOf( @@ -628,7 +628,12 @@ class DevDataBootstrap( "Hvilken tekst bruker mest fakta og minst følelsespress?", "Which text uses the most facts and the least emotional pressure?", ), - metadataJson = null, + metadataJson = """ + {"articles":[ + {"optionOrder":1,"domain":null,"headline":{"nb":"Tre klasser testet lesetidene sine i to uker","en":"Three classes tested their reading times for two weeks"},"body":{"nb":"og skrev ned resultatene.","en":"and wrote down the results."},"mediaUrl":null}, + {"optionOrder":2,"domain":null,"headline":{"nb":"Alle er rasende etter den utrolig skumle nyheten","en":"Everyone is furious after the incredibly scary news"},"body":{"nb":"som sprer seg overalt.","en":"spreading everywhere."},"mediaUrl":null} + ]} + """.trimIndent(), options = listOf( explainedOption( 1, diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt index 356143a8..644174ae 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt @@ -789,6 +789,42 @@ class TaskApiIntegrationTests { } """.trimIndent() + private fun jsonString(value: String): String = jsonMapper.writeValueAsString(value) + + private fun newsComparisonMetadataJson(): String = + """ + { + "articles": [ + { + "optionOrder": 1, + "domain": "clickbait.example", + "headline": { + "nb": "Sensasjonell artikkel", + "en": "Sensational article" + }, + "body": { + "nb": "Denne artikkelen bruker sensasjonelt språk og udokumenterte påstander.", + "en": "This article uses sensational language and makes unsupported claims." + }, + "mediaUrl": null + }, + { + "optionOrder": 2, + "domain": "news.example", + "headline": { + "nb": "Nøktern artikkel", + "en": "Measured article" + }, + "body": { + "nb": "Denne artikkelen oppgir kilde og forklarer fakta på en etterprøvbar måte.", + "en": "This article names its source and explains the facts in a verifiable way." + }, + "mediaUrl": null + } + ] + } + """.trimIndent() + private fun newsComparisonTaskPayload(stopId: Long): String = """ { @@ -804,7 +840,7 @@ class TaskApiIntegrationTests { { "itemOrder": 1, "promptText": {"nb":"Hvilken artikkel er mest troverdig?","en":"Which article is most trustworthy?"}, - "metadataJson": "{\"articles\":[{\"optionOrder\":1,\"domain\":\"clickbait.example\",\"mediaUrl\":null},{\"optionOrder\":2,\"domain\":\"news.example\",\"mediaUrl\":null}]}", + "metadataJson": ${jsonString(newsComparisonMetadataJson())}, "options": [ { "optionOrder": 1, From 3ef3a4e87c6020a1aaf6adee67bf3b67174a16f6 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:08:05 +0200 Subject: [PATCH 15/16] allow resubmission --- .../game/tasks/application/TaskService.kt | 3 - .../game/tasks/TaskApiIntegrationTests.kt | 56 ++++++++++++++++++- 2 files changed, 54 insertions(+), 5 deletions(-) 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 9dddaf88..ebde085f 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 @@ -188,9 +188,6 @@ class TaskService( if (progress.status == StopProgressStatus.LOCKED) { throw ResponseStatusException(HttpStatus.FORBIDDEN, "Stop is locked") } - if (progress.status == StopProgressStatus.COMPLETED) { - throw ResponseStatusException(HttpStatus.CONFLICT, "Stop has already been completed") - } val tasks = taskRepository.findAllByClassroomIdAndStopIdOrderByDifficultyLevelAsc(command.classroomId, command.stopId) .filter { it.isPublished } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt index 644174ae..539f983a 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/TaskApiIntegrationTests.kt @@ -479,7 +479,7 @@ class TaskApiIntegrationTests { } @Test - fun `completed stop cannot be submitted again`() { + fun `completed stop can be submitted again and keeps highest score`() { val owner = userRepository.save(activeTeacher("owner@example.com")) val classroom = createClassroom(owner, "TASK50") val stop = createMapStop(slug = "nyhetskvartalet", title = "News Quarter", displayOrder = 1) @@ -498,6 +498,7 @@ class TaskApiIntegrationTests { val taskId = createdBody.get("id").asLong() val taskItemId = createdBody.get("items")[0].get("id").asLong() val correctOptionId = createdBody.get("items")[0].get("options")[1].get("id").asLong() + val wrongOptionId = createdBody.get("items")[0].get("options")[0].get("id").asLong() mockMvc.patch("/api/v1/classrooms/${classroom.id}/tasks/$taskId/publish") { with(csrf()) @@ -512,8 +513,51 @@ class TaskApiIntegrationTests { classroom.addPupilMembership(pupil) classroomRepository.saveAndFlush(classroom) createStopProgress(pupil, classroom, stop, StopProgressStatus.COMPLETED) + // Set initial best score to 50 + val progress = pupilStopProgressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId( + requireNotNull(pupil.id), + requireNotNull(classroom.id), + requireNotNull(stop.id), + ) + progress?.bestScore = 50 + pupilStopProgressRepository.save(progress!!) + val pupilAccessToken = pupilAccessToken("submitter_completed", "secret123") + // 1. Submit with a lower score + mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks/submit-stop") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilAccessToken") + content = """ + { + "stopId": ${requireNotNull(stop.id)}, + "taskAnswers": [ + { + "taskId": $taskId, + "itemAnswers": [ + { + "itemId": $taskItemId, + "selectedOptionId": $wrongOptionId + } + ] + } + ] + } + """.trimIndent() + }.andExpect { + status { isOk() } + jsonPath("$.score") { value(0) } + } + + val progressAfterLower = pupilStopProgressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId( + requireNotNull(pupil.id), + requireNotNull(classroom.id), + requireNotNull(stop.id), + ) + assertEquals(50, progressAfterLower?.bestScore) + + // 2. Submit with a higher score mockMvc.post("/api/v1/classrooms/${classroom.id}/tasks/submit-stop") { with(csrf()) contentType = MediaType.APPLICATION_JSON @@ -535,8 +579,16 @@ class TaskApiIntegrationTests { } """.trimIndent() }.andExpect { - status { isConflict() } + status { isOk() } + jsonPath("$.score") { value(100) } } + + val progressAfterHigher = pupilStopProgressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId( + requireNotNull(pupil.id), + requireNotNull(classroom.id), + requireNotNull(stop.id), + ) + assertEquals(100, progressAfterHigher?.bestScore) } @Test From c273f2207841aefa471b4222e8c7c3744fa9db35 Mon Sep 17 00:00:00 2001 From: eilifhl Date: Wed, 22 Apr 2026 13:51:56 +0200 Subject: [PATCH 16/16] kdocs --- .../mapstops/application/MapStopService.kt | 3 ++ .../backend/game/tasks/api/TaskApiMappings.kt | 6 +++ .../backend/game/tasks/api/TaskController.kt | 3 ++ .../backend/game/tasks/api/TaskRequests.kt | 9 ++++ .../backend/game/tasks/api/TaskResponses.kt | 6 +++ .../game/tasks/application/TaskModels.kt | 15 ++++++ .../game/tasks/application/TaskService.kt | 54 +++++++++++++++++++ 7 files changed, 96 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt index ade109a6..c996cdf0 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/MapStopService.kt @@ -128,6 +128,9 @@ class MapStopService( ) } + /** + * Loads the total max score for all published tasks at each stop in a classroom. + */ private fun loadPublishedStopMaxScores(classroomId: Long): Map = taskRepository.findAllByClassroomIdOrderByStopIdAscDifficultyLevelAsc(classroomId) .asSequence() diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt index 428a2498..fb077525 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskApiMappings.kt @@ -71,6 +71,9 @@ private fun LocalizedText.toResponse(): LocalizedTextResponse = private fun LocalizedOptionalText.toResponse(): LocalizedOptionalTextResponse = LocalizedOptionalTextResponse(nb = nb, en = en) +/** + * Maps the stop submission result to the API response. + */ fun StopSubmissionResult.toResponse(): StopSubmissionResponse = StopSubmissionResponse( stopId = stopId, @@ -82,6 +85,9 @@ fun StopSubmissionResult.toResponse(): StopSubmissionResponse = taskResults = taskResults.map { it.toResponse() }, ) +/** + * Maps a single task submission result to the API response. + */ private fun TaskSubmissionResult.toResponse(): TaskSubmissionResultResponse = TaskSubmissionResultResponse( taskId = taskId, 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 b5bd820e..9be6c621 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 @@ -51,6 +51,9 @@ class TaskController( .getTask(currentUser, classroomId, taskId) .let { it.task.toResponse(includeAnswers = it.includeAnswers) } + /** + * Submits answers for all published tasks at a stop. + */ @PostMapping("/submit-stop") fun submitStopAnswers( @PathVariable classroomId: Long, 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 d5dd07d0..3479fcce 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 @@ -61,6 +61,9 @@ data class TaskItemRequest( val options: List = emptyList(), ) +/** + * Request payload for submitting answers for all tasks at a stop. + */ data class SubmitStopAnswersRequest( @field:Min(1) val stopId: Long, @@ -68,6 +71,9 @@ data class SubmitStopAnswersRequest( val taskAnswers: List = emptyList(), ) +/** + * Request payload for answers to a specific task. + */ data class SubmitTaskAnswerRequest( @field:Min(1) val taskId: Long, @@ -75,6 +81,9 @@ data class SubmitTaskAnswerRequest( val itemAnswers: List = emptyList(), ) +/** + * Request payload for the selected option of a specific task item. + */ data class SubmitItemAnswerRequest( @field:Min(1) val itemId: Long, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt index 28bf8abc..aafd8f00 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/tasks/api/TaskResponses.kt @@ -82,6 +82,9 @@ data class TaskSummaryResponse( val updatedAt: Instant?, ) +/** + * Response shape for the result of a single task submission. + */ data class TaskSubmissionResultResponse( val taskId: Long, val title: LocalizedTextResponse, @@ -91,6 +94,9 @@ data class TaskSubmissionResultResponse( val feedbackText: LocalizedOptionalTextResponse?, ) +/** + * Response shape for the result of a stop submission. + */ data class StopSubmissionResponse( val stopId: Long, val passed: Boolean, 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 5e92f752..f4909c43 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 @@ -143,6 +143,9 @@ data class TaskSummary( val updatedAt: Instant?, ) +/** + * Command used to submit answers for all tasks at a given stop. + */ data class SubmitStopAnswersCommand( val authenticatedSubject: String, val classroomId: Long, @@ -150,16 +153,25 @@ data class SubmitStopAnswersCommand( val taskAnswers: List, ) +/** + * Command containing answers for a specific task. + */ data class SubmitTaskAnswerCommand( val taskId: Long, val itemAnswers: List, ) +/** + * Command containing the selected option for a specific task item. + */ data class SubmitItemAnswerCommand( val itemId: Long, val selectedOptionId: Long, ) +/** + * The result of a stop submission, including overall score and individual task results. + */ data class StopSubmissionResult( val stopId: Long, val passed: Boolean, @@ -170,6 +182,9 @@ data class StopSubmissionResult( val taskResults: List, ) +/** + * The result of a single task submission. + */ data class TaskSubmissionResult( val taskId: Long, val title: LocalizedText, 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 ebde085f..d0afbd8b 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 @@ -40,6 +40,15 @@ class TaskService( private val pupilStopProgressService: PupilStopProgressService, private val gameAccessContextResolver: GameAccessContextResolver, ) { + /** + * Lists tasks for a classroom, optionally filtered by stop. + * + * @param currentUser The user requesting the list. + * @param classroomId The ID of the classroom. + * @param stopId Optional stop ID to filter tasks. + * @param readMode The read mode to determine access level. + * @return A list of task summaries. + */ @Transactional(readOnly = true) fun listTasks( currentUser: CurrentUser, @@ -58,6 +67,16 @@ class TaskService( .map { it.toSummary() } } + /** + * Retrieves a specific task by its ID. + * + * @param currentUser The user requesting the task. + * @param classroomId The ID of the classroom. + * @param taskId The ID of the task. + * @param readMode The read mode to determine access level. + * @return The task details and whether answers are included. + * @throws ResponseStatusException if the user cannot view unpublished tasks. + */ @Transactional(readOnly = true) fun getTask( currentUser: CurrentUser, @@ -76,6 +95,12 @@ class TaskService( ) } + /** + * Creates a new task for a classroom. + * + * @param command The command containing task details. + * @return The created task details. + */ @Transactional fun createTask(command: CreateTaskCommand): TaskDetails { val teacher = currentUserResolver.requireTeacherOrAdmin(command.authenticatedSubject) @@ -109,6 +134,12 @@ class TaskService( return saveTask(task).toDetails() } + /** + * Updates an existing task. + * + * @param command The command containing updated task details. + * @return The updated task details. + */ @Transactional fun updateTask(command: UpdateTaskCommand): TaskDetails { requireOwnedClassroom(command.authenticatedSubject, command.classroomId) @@ -149,6 +180,15 @@ class TaskService( return saveTask(task).toDetails() } + /** + * Updates the publication state of a task. + * + * @param currentUser The user performing the update. + * @param classroomId The ID of the classroom. + * @param taskId The ID of the task. + * @param published The new publication state. + * @return The updated task details. + */ @Transactional fun updatePublishState( currentUser: CurrentUser, @@ -165,6 +205,13 @@ class TaskService( return saveTask(task).toDetails() } + /** + * Deletes a task from a classroom. + * + * @param currentUser The user performing the deletion. + * @param classroomId The ID of the classroom. + * @param taskId The ID of the task. + */ @Transactional fun deleteTask( currentUser: CurrentUser, @@ -176,6 +223,13 @@ class TaskService( taskRepository.delete(task) } + /** + * Submits answers for all published tasks at a stop. + * + * @param command The command containing the submitted answers. + * @return The result of the stop submission. + * @throws ResponseStatusException if submission is invalid or forbidden. + */ @Transactional fun submitStopAnswers(command: SubmitStopAnswersCommand): StopSubmissionResult { val (_, user) = requireParticipatingClassroom(command.authenticatedSubject, command.classroomId)