From 6b54dc71d394fe0ad591ffe276bf08d1429bf127 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Wed, 22 Apr 2026 14:58:08 +0200 Subject: [PATCH 01/15] Add teacher notification module --- .../api/NotificationApiMappings.kt | 42 +++ .../api/NotificationController.kt | 80 +++++ .../api/NotificationMuteResponse.kt | 10 + .../api/NotificationPageResponse.kt | 9 + .../notification/api/NotificationResponse.kt | 18 + .../api/NotificationSummaryResponse.kt | 5 + .../ClassroomNotificationRecipientResolver.kt | 28 ++ .../NotificationDeliveryService.kt | 75 ++++ .../application/NotificationDraft.kt | 19 + .../NotificationEventContextResolver.kt | 58 +++ .../application/NotificationInboxService.kt | 98 +++++ .../application/NotificationMuteService.kt | 71 ++++ .../application/NotificationPage.kt | 11 + .../application/NotificationSummary.kt | 5 + .../TeacherNotificationEventListener.kt | 123 +++++++ .../domain/NotificationSourceKind.kt | 10 + .../notification/domain/NotificationType.kt | 11 + .../domain/TeacherNotification.kt | 58 +++ .../domain/TeacherNotificationMute.kt | 33 ++ .../TeacherNotificationMuteRepository.kt | 23 ++ .../TeacherNotificationRepository.kt | 58 +++ .../backend/shared/events/DomainEvent.kt | 10 + .../shared/events/DomainEventPublisher.kt | 5 + .../shared/events/MapStopCompletedEvent.kt | 10 + .../shared/events/PupilGameCompletedEvent.kt | 10 + .../events/PupilRecoveredFromStuckEvent.kt | 10 + .../events/PupilStuckThresholdReachedEvent.kt | 11 + .../events/SpringDomainEventPublisher.kt | 13 + .../events/WeeklyMysterySubmittedEvent.kt | 10 + ...16__create_teacher_notifications_table.sql | 34 ++ ...reate_teacher_notification_mutes_table.sql | 18 + .../NotificationControllerIntegrationTests.kt | 334 ++++++++++++++++++ .../NotificationDeliveryServiceTests.kt | 145 ++++++++ .../NotificationInboxServiceTests.kt | 107 ++++++ .../NotificationPersistenceTests.kt | 194 ++++++++++ 35 files changed, 1756 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationType.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotificationMute.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEvent.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEventPublisher.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/MapStopCompletedEvent.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilGameCompletedEvent.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilRecoveredFromStuckEvent.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilStuckThresholdReachedEvent.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/SpringDomainEventPublisher.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/WeeklyMysterySubmittedEvent.kt create mode 100644 src/main/resources/db/migration/V16__create_teacher_notifications_table.sql create mode 100644 src/main/resources/db/migration/V17__create_teacher_notification_mutes_table.sql create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt new file mode 100644 index 00000000..b4e94334 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt @@ -0,0 +1,42 @@ +package edu.ntnu.idi.idatt.backend.notification.api + +import edu.ntnu.idi.idatt.backend.notification.application.NotificationPage +import edu.ntnu.idi.idatt.backend.notification.application.NotificationSummary +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute + +fun TeacherNotification.toResponse(): NotificationResponse = + NotificationResponse( + id = requireNotNull(id) { "Notification is missing an id" }, + classroomId = classroomId, + pupilUserId = pupilUserId, + type = type, + title = title, + message = message, + payloadJson = payloadJson, + readAt = readAt, + dismissedAt = dismissedAt, + resolvedAt = resolvedAt, + createdAt = createdAt, + ) + +fun NotificationPage.toResponse(): NotificationPageResponse = + NotificationPageResponse( + items = items.map(TeacherNotification::toResponse), + page = page, + size = size, + totalElements = totalElements, + totalPages = totalPages, + ) + +fun NotificationSummary.toResponse(): NotificationSummaryResponse = + NotificationSummaryResponse( + unreadCount = unreadCount, + ) + +fun TeacherNotificationMute.toResponse(): NotificationMuteResponse = + NotificationMuteResponse( + classroomId = classroomId, + type = type, + createdAt = createdAt, + ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt new file mode 100644 index 00000000..f39d2cc2 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt @@ -0,0 +1,80 @@ +package edu.ntnu.idi.idatt.backend.notification.api + +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import edu.ntnu.idi.idatt.backend.notification.application.NotificationInboxService +import edu.ntnu.idi.idatt.backend.notification.application.NotificationMuteService +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import org.springframework.security.core.annotation.AuthenticationPrincipal +import org.springframework.web.bind.annotation.DeleteMapping +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PatchMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.PutMapping +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("/api/v1/users/me/notifications") +class NotificationController( + private val notificationInboxService: NotificationInboxService, + private val notificationMuteService: NotificationMuteService, +) { + @GetMapping + fun getNotifications( + @AuthenticationPrincipal currentUser: CurrentUser, + @RequestParam(required = false) classroomId: Long?, + @RequestParam(required = false) type: NotificationType?, + @RequestParam(defaultValue = "false") unreadOnly: Boolean, + @RequestParam(defaultValue = "0") page: Int, + @RequestParam(defaultValue = "20") size: Int, + ): NotificationPageResponse = + notificationInboxService + .getInbox(currentUser.subject, classroomId, type, unreadOnly, page, size) + .toResponse() + + @GetMapping("/summary") + fun getNotificationSummary( + @AuthenticationPrincipal currentUser: CurrentUser, + ): NotificationSummaryResponse = + notificationInboxService.getSummary(currentUser.subject).toResponse() + + @PatchMapping("/{notificationId}/read") + fun markNotificationRead( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable notificationId: Long, + ): NotificationResponse = + notificationInboxService.markRead(currentUser.subject, notificationId).toResponse() + + @PatchMapping("/{notificationId}/dismiss") + fun dismissNotification( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable notificationId: Long, + ): NotificationResponse = + notificationInboxService.dismiss(currentUser.subject, notificationId).toResponse() + + @GetMapping("/mutes") + fun getMutes( + @AuthenticationPrincipal currentUser: CurrentUser, + ): List = + notificationMuteService + .listMutes(currentUser.subject) + .map { mute -> mute.toResponse() } + + @PutMapping("/mutes/{classroomId}/{type}") + fun mute( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + @PathVariable type: NotificationType, + ): NotificationMuteResponse = + notificationMuteService.mute(currentUser.subject, classroomId, type).toResponse() + + @DeleteMapping("/mutes/{classroomId}/{type}") + fun unmute( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + @PathVariable type: NotificationType, + ) { + notificationMuteService.unmute(currentUser.subject, classroomId, type) + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt new file mode 100644 index 00000000..526320e0 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.notification.api + +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import java.time.Instant + +data class NotificationMuteResponse( + val classroomId: Long, + val type: NotificationType, + val createdAt: Instant?, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt new file mode 100644 index 00000000..074ef567 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt @@ -0,0 +1,9 @@ +package edu.ntnu.idi.idatt.backend.notification.api + +data class NotificationPageResponse( + val items: List, + val page: Int, + val size: Int, + val totalElements: Long, + val totalPages: Int, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt new file mode 100644 index 00000000..f2f238a6 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt @@ -0,0 +1,18 @@ +package edu.ntnu.idi.idatt.backend.notification.api + +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import java.time.Instant + +data class NotificationResponse( + val id: Long, + val classroomId: Long, + val pupilUserId: Long?, + val type: NotificationType, + val title: String, + val message: String, + val payloadJson: String?, + val readAt: Instant?, + val dismissedAt: Instant?, + val resolvedAt: Instant?, + val createdAt: Instant?, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt new file mode 100644 index 00000000..99488d5a --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt @@ -0,0 +1,5 @@ +package edu.ntnu.idi.idatt.backend.notification.api + +data class NotificationSummaryResponse( + val unreadCount: Long, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt new file mode 100644 index 00000000..562cfe81 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt @@ -0,0 +1,28 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import org.springframework.http.HttpStatus +import org.springframework.stereotype.Component +import org.springframework.web.server.ResponseStatusException + +/** + * Resolves the teacher recipients that administer one classroom. + */ +@Component +class ClassroomNotificationRecipientResolver( + private val classroomRepository: ClassroomRepository, +) { + fun resolveTeacherRecipientIds(classroomId: Long): Set { + val classroom = classroomRepository.findById(classroomId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + } + + return buildSet { + add(classroom.ownerTeacherId) + classroom.teacherMemberships + .mapNotNull { membership -> membership.teacher?.id } + .forEach(::add) + } + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt new file mode 100644 index 00000000..54c0119e --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt @@ -0,0 +1,75 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import java.time.Instant + +/** + * Handles teacher fan-out, mute checks, and active-thread deduplication. + */ +@Service +class NotificationDeliveryService( + private val teacherNotificationRepository: TeacherNotificationRepository, + private val teacherNotificationMuteRepository: TeacherNotificationMuteRepository, + private val recipientResolver: ClassroomNotificationRecipientResolver, +) { + @Transactional + fun deliverToClassroomTeachers(draft: NotificationDraft): List { + val recipients = recipientResolver.resolveTeacherRecipientIds(draft.classroomId) + + val notifications = recipients + .filterNot { teacherUserId -> + teacherNotificationMuteRepository.existsByTeacherUserIdAndClassroomIdAndType( + teacherUserId = teacherUserId, + classroomId = draft.classroomId, + type = draft.type, + ) + } + .filterNot { teacherUserId -> + draft.threadKey != null && + teacherNotificationRepository.findActiveThreadNotifications(teacherUserId, draft.threadKey).isNotEmpty() + } + .map { teacherUserId -> + TeacherNotification( + teacherUserId = teacherUserId, + classroomId = draft.classroomId, + pupilUserId = draft.pupilUserId, + type = draft.type, + sourceKind = draft.sourceKind, + sourceKey = draft.sourceKey, + threadKey = draft.threadKey, + title = draft.title, + message = draft.message, + payloadJson = draft.payloadJson, + ) + } + + if (notifications.isEmpty()) { + return emptyList() + } + + return teacherNotificationRepository.saveAll(notifications) + } + + @Transactional + fun resolveThread(classroomId: Long, threadKey: String): Int { + val now = Instant.now() + val activeNotifications = teacherNotificationRepository.findAllByClassroomIdAndThreadKeyAndResolvedAtIsNull( + classroomId = classroomId, + threadKey = threadKey, + ) + + if (activeNotifications.isEmpty()) { + return 0 + } + + activeNotifications.forEach { notification -> + notification.resolvedAt = now + } + teacherNotificationRepository.saveAll(activeNotifications) + return activeNotifications.size + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt new file mode 100644 index 00000000..b9ab72ec --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt @@ -0,0 +1,19 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType + +/** + * Fully formatted teacher notification ready for fan-out. + */ +data class NotificationDraft( + val classroomId: Long, + val pupilUserId: Long?, + val type: NotificationType, + val sourceKind: NotificationSourceKind, + val sourceKey: String, + val threadKey: String?, + val title: String, + val message: String, + val payloadJson: String?, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt new file mode 100644 index 00000000..af0c80fb --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt @@ -0,0 +1,58 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import com.fasterxml.jackson.databind.json.JsonMapper +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository +import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.users.profile.infrastructure.PupilProfileRepository +import org.springframework.http.HttpStatus +import org.springframework.stereotype.Component +import org.springframework.web.server.ResponseStatusException + +data class StopNotificationContext( + val classroomTitle: String, + val pupilDisplayName: String, + val stopTitle: String, +) + +/** + * Resolves user-facing names needed to format teacher notifications. + */ +@Component +class NotificationEventContextResolver( + private val classroomRepository: ClassroomRepository, + private val pupilProfileRepository: PupilProfileRepository, + private val userRepository: UserRepository, + private val mapStopsRepository: MapStopsRepository, +) { + private val objectMapper = JsonMapper.builder().build() + + fun resolveStopContext( + classroomId: Long, + pupilUserId: Long, + stopId: Long, + ): StopNotificationContext { + val classroom = classroomRepository.findById(classroomId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + } + val pupilProfile = pupilProfileRepository.findById(pupilUserId).orElse(null) + val pupil = userRepository.findById(pupilUserId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil not found") + } + val stop = mapStopsRepository.findById(stopId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Map stop not found") + } + + return StopNotificationContext( + classroomTitle = classroom.title, + pupilDisplayName = pupilProfile?.displayName ?: pupil.username ?: "Elev", + stopTitle = stop.title ?: stop.slug ?: "ukjent omrade", + ) + } + + fun payloadJson(vararg entries: Pair): String = + objectMapper.writeValueAsString(linkedMapOf(*entries)) +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt new file mode 100644 index 00000000..ed0f234e --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt @@ -0,0 +1,98 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.springframework.data.domain.PageRequest +import org.springframework.http.HttpStatus +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import org.springframework.web.server.ResponseStatusException +import java.time.Instant + +/** + * Handles personal teacher inbox reads and state transitions. + */ +@Service +class NotificationInboxService( + private val teacherNotificationRepository: TeacherNotificationRepository, + private val currentUserResolver: CurrentUserResolver, +) { + @Transactional(readOnly = true) + fun getInbox( + authenticatedSubject: String, + classroomId: Long?, + type: NotificationType?, + unreadOnly: Boolean, + page: Int, + size: Int, + ): NotificationPage { + val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + val requestedPage = page.coerceAtLeast(0) + val requestedSize = size.coerceIn(1, 100) + val inboxPage = teacherNotificationRepository.findInboxPage( + teacherUserId = teacherId, + classroomId = classroomId, + type = type, + unreadOnly = unreadOnly, + pageable = PageRequest.of(requestedPage, requestedSize), + ) + + return NotificationPage( + items = inboxPage.content, + page = inboxPage.number, + size = inboxPage.size, + totalElements = inboxPage.totalElements, + totalPages = inboxPage.totalPages, + ) + } + + @Transactional(readOnly = true) + fun getSummary(authenticatedSubject: String): NotificationSummary { + val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + return NotificationSummary( + unreadCount = teacherNotificationRepository.countByTeacherUserIdAndReadAtIsNullAndDismissedAtIsNull(teacherId), + ) + } + + @Transactional + fun markRead( + authenticatedSubject: String, + notificationId: Long, + ): TeacherNotification { + val notification = requireTeacherNotification(authenticatedSubject, notificationId) + if (notification.readAt == null) { + notification.readAt = Instant.now() + } + return teacherNotificationRepository.save(notification) + } + + @Transactional + fun dismiss( + authenticatedSubject: String, + notificationId: Long, + ): TeacherNotification { + val notification = requireTeacherNotification(authenticatedSubject, notificationId) + val now = Instant.now() + if (notification.readAt == null) { + notification.readAt = now + } + if (notification.dismissedAt == null) { + notification.dismissedAt = now + } + return teacherNotificationRepository.save(notification) + } + + private fun requireTeacherNotification( + authenticatedSubject: String, + notificationId: Long, + ): TeacherNotification { + val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + return teacherNotificationRepository.findByIdAndTeacherUserId(notificationId, teacherId) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Notification not found") + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt new file mode 100644 index 00000000..e37f1bcc --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt @@ -0,0 +1,71 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import edu.ntnu.idi.idatt.backend.iam.application.ClassroomUserResolver +import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional + +/** + * Handles teacher-specific mute preferences. + */ +@Service +class NotificationMuteService( + private val teacherNotificationMuteRepository: TeacherNotificationMuteRepository, + private val currentUserResolver: CurrentUserResolver, + private val classroomUserResolver: ClassroomUserResolver, +) { + @Transactional(readOnly = true) + fun listMutes(authenticatedSubject: String): List { + val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + return teacherNotificationMuteRepository.findAllByTeacherUserIdOrderByClassroomIdAscTypeAsc(teacherId) + } + + @Transactional + fun mute( + authenticatedSubject: String, + classroomId: Long, + type: NotificationType, + ): TeacherNotificationMute { + val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + classroomUserResolver.requireClassroomTeacherAccess(teacher, classroomId) + + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + val existingMute = teacherNotificationMuteRepository.findByTeacherUserIdAndClassroomIdAndType( + teacherUserId = teacherId, + classroomId = classroomId, + type = type, + ) + if (existingMute != null) { + return existingMute + } + + return teacherNotificationMuteRepository.save( + TeacherNotificationMute( + teacherUserId = teacherId, + classroomId = classroomId, + type = type, + ), + ) + } + + @Transactional + fun unmute( + authenticatedSubject: String, + classroomId: Long, + type: NotificationType, + ) { + val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + classroomUserResolver.requireClassroomTeacherAccess(teacher, classroomId) + + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + teacherNotificationMuteRepository.findByTeacherUserIdAndClassroomIdAndType( + teacherUserId = teacherId, + classroomId = classroomId, + type = type, + )?.let(teacherNotificationMuteRepository::delete) + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt new file mode 100644 index 00000000..34d3cf60 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt @@ -0,0 +1,11 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification + +data class NotificationPage( + val items: List, + val page: Int, + val size: Int, + val totalElements: Long, + val totalPages: Int, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt new file mode 100644 index 00000000..e69b818f --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt @@ -0,0 +1,5 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +data class NotificationSummary( + val unreadCount: Long, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt new file mode 100644 index 00000000..e3986678 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt @@ -0,0 +1,123 @@ +package edu.ntnu.idi.idatt.backend.notification.application + +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent +import org.springframework.context.event.EventListener +import org.springframework.stereotype.Component + +/** + * Translates business events into teacher inbox notifications after commit. + */ +@Component +class TeacherNotificationEventListener( + private val notificationDeliveryService: NotificationDeliveryService, + private val notificationEventContextResolver: NotificationEventContextResolver, +) { + @EventListener + fun onMapStopCompleted(event: MapStopCompletedEvent) { + val context = notificationEventContextResolver.resolveStopContext( + classroomId = event.classroomId, + pupilUserId = event.pupilUserId, + stopId = event.stopId, + ) + val threadKey = stopCompletedThreadKey(event.classroomId, event.pupilUserId, event.stopId) + + notificationDeliveryService.deliverToClassroomTeachers( + NotificationDraft( + classroomId = event.classroomId, + pupilUserId = event.pupilUserId, + type = NotificationType.MAP_STOP_COMPLETED, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = threadKey, + threadKey = threadKey, + title = "Omrade fullfort", + message = "${context.pupilDisplayName} har fullfort omradet ${context.stopTitle} i ${context.classroomTitle}.", + payloadJson = notificationEventContextResolver.payloadJson( + "classroomId" to event.classroomId, + "pupilUserId" to event.pupilUserId, + "stopId" to event.stopId, + ), + ), + ) + } + + @EventListener + fun onGameCompleted(event: PupilGameCompletedEvent) { + val context = notificationEventContextResolver.resolveStopContext( + classroomId = event.classroomId, + pupilUserId = event.pupilUserId, + stopId = event.stopId, + ) + val threadKey = gameCompletedThreadKey(event.classroomId, event.pupilUserId) + + notificationDeliveryService.deliverToClassroomTeachers( + NotificationDraft( + classroomId = event.classroomId, + pupilUserId = event.pupilUserId, + type = NotificationType.GAME_COMPLETED, + sourceKind = NotificationSourceKind.GAME_PROGRESS, + sourceKey = threadKey, + threadKey = threadKey, + title = "Spillet fullfort", + message = "${context.pupilDisplayName} har fullfort spillet i ${context.classroomTitle}.", + payloadJson = notificationEventContextResolver.payloadJson( + "classroomId" to event.classroomId, + "pupilUserId" to event.pupilUserId, + "stopId" to event.stopId, + ), + ), + ) + } + + @EventListener + fun onPupilStuck(event: PupilStuckThresholdReachedEvent) { + val context = notificationEventContextResolver.resolveStopContext( + classroomId = event.classroomId, + pupilUserId = event.pupilUserId, + stopId = event.stopId, + ) + val threadKey = stuckThreadKey(event.classroomId, event.pupilUserId, event.stopId) + + notificationDeliveryService.deliverToClassroomTeachers( + NotificationDraft( + classroomId = event.classroomId, + pupilUserId = event.pupilUserId, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = threadKey, + threadKey = threadKey, + title = "Elev star fast", + message = "${context.pupilDisplayName} star fast ved ${context.stopTitle} i ${context.classroomTitle}.", + payloadJson = notificationEventContextResolver.payloadJson( + "classroomId" to event.classroomId, + "pupilUserId" to event.pupilUserId, + "stopId" to event.stopId, + "consecutiveWrongAttempts" to event.consecutiveWrongAttempts, + ), + ), + ) + } + + @EventListener + fun onPupilRecovered(event: PupilRecoveredFromStuckEvent) { + notificationDeliveryService.resolveThread( + classroomId = event.classroomId, + threadKey = stuckThreadKey(event.classroomId, event.pupilUserId, event.stopId), + ) + } + + companion object { + fun stopCompletedThreadKey(classroomId: Long, pupilUserId: Long, stopId: Long): String = + "stop-completed:$classroomId:$pupilUserId:$stopId" + + fun gameCompletedThreadKey(classroomId: Long, pupilUserId: Long): String = + "game-completed:$classroomId:$pupilUserId" + + fun stuckThreadKey(classroomId: Long, pupilUserId: Long, stopId: Long): String = + "stuck:$classroomId:$pupilUserId:$stopId" + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt new file mode 100644 index 00000000..8f3cbaca --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.notification.domain + +/** + * Identifies the business source that produced a teacher notification. + */ +enum class NotificationSourceKind { + MAP_STOP_PROGRESS, + GAME_PROGRESS, + WEEKLY_MYSTERY_SUBMISSION, +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationType.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationType.kt new file mode 100644 index 00000000..6628c231 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationType.kt @@ -0,0 +1,11 @@ +package edu.ntnu.idi.idatt.backend.notification.domain + +/** + * Supported teacher notification categories. + */ +enum class NotificationType { + MAP_STOP_COMPLETED, + GAME_COMPLETED, + PUPIL_STUCK, + WEEKLY_MYSTERY_SUBMITTED, +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt new file mode 100644 index 00000000..8f338eb7 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt @@ -0,0 +1,58 @@ +package edu.ntnu.idi.idatt.backend.notification.domain + +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.EnumType +import jakarta.persistence.Enumerated +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.Table +import org.hibernate.annotations.CreationTimestamp +import org.hibernate.annotations.UpdateTimestamp +import java.time.Instant + +/** + * Persisted inbox item delivered to one teacher. + */ +@Entity +@Table(name = "teacher_notifications") +class TeacherNotification( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long? = null, + @Column(name = "teacher_user_id", nullable = false) + var teacherUserId: Long, + @Column(name = "classroom_id", nullable = false) + var classroomId: Long, + @Column(name = "pupil_user_id") + var pupilUserId: Long? = null, + @Enumerated(EnumType.STRING) + @Column(nullable = false) + var type: NotificationType, + @Enumerated(EnumType.STRING) + @Column(name = "source_kind", nullable = false) + var sourceKind: NotificationSourceKind, + @Column(name = "source_key", nullable = false, length = 255) + var sourceKey: String, + @Column(name = "thread_key", length = 255) + var threadKey: String? = null, + @Column(nullable = false, length = 255) + var title: String, + @Column(nullable = false, columnDefinition = "TEXT") + var message: String, + @Column(name = "payload_json", columnDefinition = "TEXT") + var payloadJson: String? = null, + @Column(name = "read_at") + var readAt: Instant? = null, + @Column(name = "dismissed_at") + var dismissedAt: Instant? = null, + @Column(name = "resolved_at") + var resolvedAt: Instant? = null, + @CreationTimestamp + @Column(name = "created_at", nullable = false, updatable = false) + var createdAt: Instant? = null, + @UpdateTimestamp + @Column(name = "updated_at", nullable = false) + var updatedAt: Instant? = null, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotificationMute.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotificationMute.kt new file mode 100644 index 00000000..b50f17ba --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotificationMute.kt @@ -0,0 +1,33 @@ +package edu.ntnu.idi.idatt.backend.notification.domain + +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.EnumType +import jakarta.persistence.Enumerated +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.Table +import org.hibernate.annotations.CreationTimestamp +import java.time.Instant + +/** + * Teacher-specific suppression rule for one classroom and notification type. + */ +@Entity +@Table(name = "teacher_notification_mutes") +class TeacherNotificationMute( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long? = null, + @Column(name = "teacher_user_id", nullable = false) + var teacherUserId: Long, + @Column(name = "classroom_id", nullable = false) + var classroomId: Long, + @Enumerated(EnumType.STRING) + @Column(nullable = false) + var type: NotificationType, + @CreationTimestamp + @Column(name = "created_at", nullable = false, updatable = false) + var createdAt: Instant? = null, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt new file mode 100644 index 00000000..18d08af5 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt @@ -0,0 +1,23 @@ +package edu.ntnu.idi.idatt.backend.notification.infrastructure + +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +@Repository +interface TeacherNotificationMuteRepository : JpaRepository { + fun existsByTeacherUserIdAndClassroomIdAndType( + teacherUserId: Long, + classroomId: Long, + type: NotificationType, + ): Boolean + + fun findAllByTeacherUserIdOrderByClassroomIdAscTypeAsc(teacherUserId: Long): List + + fun findByTeacherUserIdAndClassroomIdAndType( + teacherUserId: Long, + classroomId: Long, + type: NotificationType, + ): TeacherNotificationMute? +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt new file mode 100644 index 00000000..3e13219b --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt @@ -0,0 +1,58 @@ +package edu.ntnu.idi.idatt.backend.notification.infrastructure + +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import org.springframework.data.domain.Page +import org.springframework.data.domain.Pageable +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.data.jpa.repository.Query +import org.springframework.data.repository.query.Param +import org.springframework.stereotype.Repository + +@Repository +interface TeacherNotificationRepository : JpaRepository { + + @Query( + """ + SELECT notification + FROM TeacherNotification notification + WHERE notification.teacherUserId = :teacherUserId + AND notification.dismissedAt IS NULL + AND (:classroomId IS NULL OR notification.classroomId = :classroomId) + AND (:type IS NULL OR notification.type = :type) + AND (:unreadOnly = FALSE OR notification.readAt IS NULL) + ORDER BY notification.createdAt DESC, notification.id DESC + """, + ) + fun findInboxPage( + @Param("teacherUserId") teacherUserId: Long, + @Param("classroomId") classroomId: Long?, + @Param("type") type: NotificationType?, + @Param("unreadOnly") unreadOnly: Boolean, + pageable: Pageable, + ): Page + + fun countByTeacherUserIdAndReadAtIsNullAndDismissedAtIsNull(teacherUserId: Long): Long + + fun findByIdAndTeacherUserId(id: Long, teacherUserId: Long): TeacherNotification? + + @Query( + """ + SELECT notification + FROM TeacherNotification notification + WHERE notification.teacherUserId = :teacherUserId + AND notification.threadKey = :threadKey + AND notification.resolvedAt IS NULL + ORDER BY notification.createdAt DESC, notification.id DESC + """, + ) + fun findActiveThreadNotifications( + @Param("teacherUserId") teacherUserId: Long, + @Param("threadKey") threadKey: String, + ): List + + fun findAllByClassroomIdAndThreadKeyAndResolvedAtIsNull( + classroomId: Long, + threadKey: String, + ): List +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEvent.kt new file mode 100644 index 00000000..7d3ba45a --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEvent.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +import java.time.Instant + +/** + * Marker interface for business events published inside the application. + */ +interface DomainEvent { + val occurredAt: Instant +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEventPublisher.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEventPublisher.kt new file mode 100644 index 00000000..757d11ca --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/DomainEventPublisher.kt @@ -0,0 +1,5 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +interface DomainEventPublisher { + fun publish(event: DomainEvent) +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/MapStopCompletedEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/MapStopCompletedEvent.kt new file mode 100644 index 00000000..4fd2c948 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/MapStopCompletedEvent.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +import java.time.Instant + +data class MapStopCompletedEvent( + val pupilUserId: Long, + val classroomId: Long, + val stopId: Long, + override val occurredAt: Instant = Instant.now(), +) : DomainEvent diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilGameCompletedEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilGameCompletedEvent.kt new file mode 100644 index 00000000..e2fedb0b --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilGameCompletedEvent.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +import java.time.Instant + +data class PupilGameCompletedEvent( + val pupilUserId: Long, + val classroomId: Long, + val stopId: Long, + override val occurredAt: Instant = Instant.now(), +) : DomainEvent diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilRecoveredFromStuckEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilRecoveredFromStuckEvent.kt new file mode 100644 index 00000000..39688e7c --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilRecoveredFromStuckEvent.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +import java.time.Instant + +data class PupilRecoveredFromStuckEvent( + val pupilUserId: Long, + val classroomId: Long, + val stopId: Long, + override val occurredAt: Instant = Instant.now(), +) : DomainEvent diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilStuckThresholdReachedEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilStuckThresholdReachedEvent.kt new file mode 100644 index 00000000..6a1f84a7 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/PupilStuckThresholdReachedEvent.kt @@ -0,0 +1,11 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +import java.time.Instant + +data class PupilStuckThresholdReachedEvent( + val pupilUserId: Long, + val classroomId: Long, + val stopId: Long, + val consecutiveWrongAttempts: Int, + override val occurredAt: Instant = Instant.now(), +) : DomainEvent diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/SpringDomainEventPublisher.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/SpringDomainEventPublisher.kt new file mode 100644 index 00000000..82c5e2c5 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/SpringDomainEventPublisher.kt @@ -0,0 +1,13 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +import org.springframework.context.ApplicationEventPublisher +import org.springframework.stereotype.Component + +@Component +class SpringDomainEventPublisher( + private val applicationEventPublisher: ApplicationEventPublisher, +) : DomainEventPublisher { + override fun publish(event: DomainEvent) { + applicationEventPublisher.publishEvent(event) + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/WeeklyMysterySubmittedEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/WeeklyMysterySubmittedEvent.kt new file mode 100644 index 00000000..a6e1f6d4 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/shared/events/WeeklyMysterySubmittedEvent.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.shared.events + +import java.time.Instant + +data class WeeklyMysterySubmittedEvent( + val pupilUserId: Long, + val classroomId: Long, + val submissionId: Long, + override val occurredAt: Instant = Instant.now(), +) : DomainEvent diff --git a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql new file mode 100644 index 00000000..134e0355 --- /dev/null +++ b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql @@ -0,0 +1,34 @@ +CREATE TABLE teacher_notifications ( + id BIGINT NOT NULL AUTO_INCREMENT, + teacher_user_id BIGINT NOT NULL, + classroom_id BIGINT NOT NULL, + pupil_user_id BIGINT, + type ENUM('MAP_STOP_COMPLETED', 'GAME_COMPLETED', 'PUPIL_STUCK', 'WEEKLY_MYSTERY_SUBMITTED') NOT NULL, + source_kind ENUM('MAP_STOP_PROGRESS', 'GAME_PROGRESS', 'WEEKLY_MYSTERY_SUBMISSION') NOT NULL, + source_key VARCHAR(255) NOT NULL, + thread_key VARCHAR(255), + title VARCHAR(255) NOT NULL, + message TEXT NOT NULL, + payload_json TEXT, + read_at DATETIME(6), + dismissed_at DATETIME(6), + resolved_at DATETIME(6), + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + CONSTRAINT pk_teacher_notifications PRIMARY KEY (id), + CONSTRAINT fk_teacher_notifications_teacher + FOREIGN KEY (teacher_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_teacher_notifications_classroom + FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE, + CONSTRAINT fk_teacher_notifications_pupil + FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE +); + +CREATE INDEX idx_teacher_notifications_teacher_created + ON teacher_notifications (teacher_user_id, created_at); +CREATE INDEX idx_teacher_notifications_teacher_classroom + ON teacher_notifications (teacher_user_id, classroom_id); +CREATE INDEX idx_teacher_notifications_teacher_type + ON teacher_notifications (teacher_user_id, type); +CREATE INDEX idx_teacher_notifications_teacher_thread + ON teacher_notifications (teacher_user_id, thread_key, resolved_at); diff --git a/src/main/resources/db/migration/V17__create_teacher_notification_mutes_table.sql b/src/main/resources/db/migration/V17__create_teacher_notification_mutes_table.sql new file mode 100644 index 00000000..34a9741d --- /dev/null +++ b/src/main/resources/db/migration/V17__create_teacher_notification_mutes_table.sql @@ -0,0 +1,18 @@ +CREATE TABLE teacher_notification_mutes ( + id BIGINT NOT NULL AUTO_INCREMENT, + teacher_user_id BIGINT NOT NULL, + classroom_id BIGINT NOT NULL, + type ENUM('MAP_STOP_COMPLETED', 'GAME_COMPLETED', 'PUPIL_STUCK', 'WEEKLY_MYSTERY_SUBMITTED') NOT NULL, + created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + CONSTRAINT pk_teacher_notification_mutes PRIMARY KEY (id), + CONSTRAINT uk_teacher_notification_mutes_scope UNIQUE (teacher_user_id, classroom_id, type), + CONSTRAINT fk_teacher_notification_mutes_teacher + FOREIGN KEY (teacher_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_teacher_notification_mutes_classroom + FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE +); + +CREATE INDEX idx_teacher_notification_mutes_teacher + ON teacher_notification_mutes (teacher_user_id); +CREATE INDEX idx_teacher_notification_mutes_teacher_classroom + ON teacher_notification_mutes (teacher_user_id, classroom_id); diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt new file mode 100644 index 00000000..51e3348d --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt @@ -0,0 +1,334 @@ +package edu.ntnu.idi.idatt.backend.notification + +import com.fasterxml.jackson.databind.json.JsonMapper +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.domain.UserRole +import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import edu.ntnu.idi.idatt.backend.iam.infrastructure.RefreshTokenRepository +import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.security.crypto.password.PasswordEncoder +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf +import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.delete +import org.springframework.test.web.servlet.get +import org.springframework.test.web.servlet.patch +import org.springframework.test.web.servlet.post +import org.springframework.test.web.servlet.put +import java.time.Instant + +@SpringBootTest +@AutoConfigureMockMvc +class NotificationControllerIntegrationTests { + @Autowired + private lateinit var mockMvc: MockMvc + + @Autowired + private lateinit var userRepository: UserRepository + + @Autowired + private lateinit var classroomRepository: ClassroomRepository + + @Autowired + private lateinit var teacherNotificationRepository: TeacherNotificationRepository + + @Autowired + private lateinit var teacherNotificationMuteRepository: TeacherNotificationMuteRepository + + @Autowired + private lateinit var refreshTokenRepository: RefreshTokenRepository + + @Autowired + private lateinit var passwordEncoder: PasswordEncoder + + private val jsonMapper = JsonMapper.builder().build() + + @BeforeEach + fun setUp() { + refreshTokenRepository.deleteAll() + teacherNotificationMuteRepository.deleteAll() + teacherNotificationRepository.deleteAll() + classroomRepository.deleteAll() + userRepository.deleteAll() + } + + @Test + fun `notifications require authentication`() { + mockMvc.get("/api/v1/users/me/notifications").andExpect { + status { isUnauthorized() } + } + } + + @Test + fun `teacher can filter personal inbox`() { + val teacher = userRepository.save(activeTeacher("owner-filter@example.com")) + val otherTeacher = userRepository.save(activeTeacher("other-filter@example.com")) + val classroom = createClassroom("NOTIFY1", teacher) + val secondClassroom = createClassroom("NOTIFY2", teacher) + + teacherNotificationRepository.saveAll( + listOf( + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.MAP_STOP_COMPLETED, + ), + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.PUPIL_STUCK, + readAt = Instant.now(), + ), + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = secondClassroom.id, + type = NotificationType.GAME_COMPLETED, + dismissedAt = Instant.now(), + ), + notification( + teacherUserId = requireNotNull(otherTeacher.id), + classroomId = classroom.id, + type = NotificationType.MAP_STOP_COMPLETED, + ), + ), + ) + + val accessToken = teacherAccessToken("owner-filter@example.com", "secret123") + + mockMvc.get("/api/v1/users/me/notifications") { + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + param("classroomId", classroom.id.toString()) + param("type", NotificationType.MAP_STOP_COMPLETED.name) + param("unreadOnly", "true") + param("page", "0") + param("size", "10") + }.andExpect { + status { isOk() } + jsonPath("$.items.length()") { value(1) } + jsonPath("$.items[0].type") { value(NotificationType.MAP_STOP_COMPLETED.name) } + jsonPath("$.totalElements") { value(1) } + } + + mockMvc.get("/api/v1/users/me/notifications/summary") { + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.unreadCount") { value(1) } + } + } + + @Test + fun `pupil cannot access teacher notifications`() { + userRepository.save(activePupil("notify-pupil")) + val accessToken = pupilAccessToken("notify-pupil", "secret123") + + mockMvc.get("/api/v1/users/me/notifications") { + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isForbidden() } + } + } + + @Test + fun `mark read is idempotent`() { + val teacher = userRepository.save(activeTeacher("owner-read@example.com")) + val classroom = createClassroom("READ1", teacher) + val notification = teacherNotificationRepository.save( + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.MAP_STOP_COMPLETED, + ), + ) + val accessToken = teacherAccessToken("owner-read@example.com", "secret123") + + mockMvc.patch("/api/v1/users/me/notifications/${notification.id}/read") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.readAt") { isNotEmpty() } + } + + mockMvc.patch("/api/v1/users/me/notifications/${notification.id}/read") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.readAt") { isNotEmpty() } + } + } + + @Test + fun `dismiss hides notification from inbox`() { + val teacher = userRepository.save(activeTeacher("owner-dismiss@example.com")) + val classroom = createClassroom("DISMISS1", teacher) + val notification = teacherNotificationRepository.save( + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.PUPIL_STUCK, + ), + ) + val accessToken = teacherAccessToken("owner-dismiss@example.com", "secret123") + + mockMvc.patch("/api/v1/users/me/notifications/${notification.id}/dismiss") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.dismissedAt") { isNotEmpty() } + jsonPath("$.readAt") { isNotEmpty() } + } + + mockMvc.get("/api/v1/users/me/notifications") { + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.items.length()") { value(0) } + } + } + + @Test + fun `teacher member can mute and unmute administered classroom notifications`() { + val owner = userRepository.save(activeTeacher("owner-mute@example.com")) + val member = userRepository.save(activeTeacher("member-mute@example.com")) + val classroom = createClassroom("MUTE1", owner) + classroom.addTeacher(member) + classroomRepository.saveAndFlush(classroom) + val accessToken = teacherAccessToken("member-mute@example.com", "secret123") + + mockMvc.put("/api/v1/users/me/notifications/mutes/${classroom.id}/${NotificationType.PUPIL_STUCK}") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.classroomId") { value(classroom.id.toInt()) } + jsonPath("$.type") { value(NotificationType.PUPIL_STUCK.name) } + } + + mockMvc.get("/api/v1/users/me/notifications/mutes") { + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.length()") { value(1) } + } + + mockMvc.delete("/api/v1/users/me/notifications/mutes/${classroom.id}/${NotificationType.PUPIL_STUCK}") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + } + + mockMvc.get("/api/v1/users/me/notifications/mutes") { + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + jsonPath("$.length()") { value(0) } + } + } + + @Test + fun `teacher cannot mute classroom they do not administer`() { + val owner = userRepository.save(activeTeacher("owner-no-mute@example.com")) + val outsider = userRepository.save(activeTeacher("outsider-no-mute@example.com")) + val classroom = createClassroom("MUTE2", owner) + val accessToken = teacherAccessToken("outsider-no-mute@example.com", "secret123") + + mockMvc.put("/api/v1/users/me/notifications/mutes/${classroom.id}/${NotificationType.PUPIL_STUCK}") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isForbidden() } + } + } + + private fun notification( + teacherUserId: Long, + classroomId: Long, + type: NotificationType, + readAt: Instant? = null, + dismissedAt: Instant? = null, + ): TeacherNotification = + TeacherNotification( + teacherUserId = teacherUserId, + classroomId = classroomId, + pupilUserId = null, + type = type, + sourceKind = when (type) { + NotificationType.MAP_STOP_COMPLETED, NotificationType.PUPIL_STUCK -> NotificationSourceKind.MAP_STOP_PROGRESS + NotificationType.GAME_COMPLETED -> NotificationSourceKind.GAME_PROGRESS + NotificationType.WEEKLY_MYSTERY_SUBMITTED -> NotificationSourceKind.WEEKLY_MYSTERY_SUBMISSION + }, + sourceKey = "${type.name.lowercase()}-${System.nanoTime()}", + threadKey = if (type == NotificationType.PUPIL_STUCK) "stuck:$classroomId:$teacherUserId" else null, + title = "Notification $type", + message = "Notification for $type", + readAt = readAt, + dismissedAt = dismissedAt, + ) + + private fun createClassroom(code: String, owner: User): Classroom = + classroomRepository.saveAndFlush( + Classroom( + ownerTeacherId = requireNotNull(owner.id), + title = "Class $code", + description = "Notification integration classroom", + joinCode = code, + status = ClassroomStatus.ACTIVE, + ), + ) + + private fun teacherAccessToken(email: String, password: String): String = + jsonMapper.readTree( + mockMvc.post("/api/v1/auth/teacher/login") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + content = """{"email":"$email","password":"$password"}""" + }.andExpect { + status { isOk() } + }.andReturn().response.contentAsString, + ).get("accessToken").asText() + + private fun pupilAccessToken(username: String, password: String): String = + jsonMapper.readTree( + mockMvc.post("/api/v1/auth/pupil/login") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + content = """{"username":"$username","password":"$password"}""" + }.andExpect { + status { isOk() } + }.andReturn().response.contentAsString, + ).get("accessToken").asText() + + private fun activeTeacher(email: String): User = + User( + email = email, + passwordHash = requireNotNull(passwordEncoder.encode("secret123")), + role = UserRole.TEACHER, + status = UserStatus.ACTIVE, + ) + + private fun activePupil(username: String): User = + User( + username = username, + passwordHash = requireNotNull(passwordEncoder.encode("secret123")), + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt new file mode 100644 index 00000000..e6a7cc28 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt @@ -0,0 +1,145 @@ +package edu.ntnu.idi.idatt.backend.notification + +import edu.ntnu.idi.idatt.backend.notification.application.ClassroomNotificationRecipientResolver +import edu.ntnu.idi.idatt.backend.notification.application.NotificationDeliveryService +import edu.ntnu.idi.idatt.backend.notification.application.NotificationDraft +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.ArgumentCaptor +import org.mockito.Mockito.anyList +import org.mockito.Mockito.mock +import org.mockito.Mockito.times +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` +import java.time.Instant + +class NotificationDeliveryServiceTests { + private lateinit var teacherNotificationRepository: TeacherNotificationRepository + private lateinit var teacherNotificationMuteRepository: TeacherNotificationMuteRepository + private lateinit var recipientResolver: ClassroomNotificationRecipientResolver + private lateinit var notificationDeliveryService: NotificationDeliveryService + + @BeforeEach + fun setUp() { + teacherNotificationRepository = mock(TeacherNotificationRepository::class.java) + teacherNotificationMuteRepository = mock(TeacherNotificationMuteRepository::class.java) + recipientResolver = mock(ClassroomNotificationRecipientResolver::class.java) + notificationDeliveryService = NotificationDeliveryService( + teacherNotificationRepository = teacherNotificationRepository, + teacherNotificationMuteRepository = teacherNotificationMuteRepository, + recipientResolver = recipientResolver, + ) + } + + @Test + fun `deliver skips muted and already active thread recipients`() { + val draft = NotificationDraft( + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "stuck-42-7-3", + threadKey = "stuck:42:7:3", + title = "Elev star fast", + message = "En elev trenger hjelp.", + payloadJson = """{"stopId":3}""", + ) + + `when`(recipientResolver.resolveTeacherRecipientIds(42L)).thenReturn(setOf(10L, 11L, 12L)) + `when`( + teacherNotificationMuteRepository.existsByTeacherUserIdAndClassroomIdAndType( + 10L, + 42L, + NotificationType.PUPIL_STUCK, + ), + ).thenReturn(false) + `when`( + teacherNotificationMuteRepository.existsByTeacherUserIdAndClassroomIdAndType( + 11L, + 42L, + NotificationType.PUPIL_STUCK, + ), + ).thenReturn(true) + `when`( + teacherNotificationMuteRepository.existsByTeacherUserIdAndClassroomIdAndType( + 12L, + 42L, + NotificationType.PUPIL_STUCK, + ), + ).thenReturn(false) + `when`(teacherNotificationRepository.findActiveThreadNotifications(10L, "stuck:42:7:3")).thenReturn(emptyList()) + `when`( + teacherNotificationRepository.findActiveThreadNotifications(12L, "stuck:42:7:3"), + ).thenReturn( + listOf( + TeacherNotification( + teacherUserId = 12L, + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "existing", + threadKey = "stuck:42:7:3", + title = "Existing", + message = "Existing", + ), + ), + ) + `when`(teacherNotificationRepository.saveAll(anyList())).thenAnswer { it.arguments[0] } + + val savedNotifications = notificationDeliveryService.deliverToClassroomTeachers(draft) + + val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> + verify(teacherNotificationRepository).saveAll(captor.capture()) + assertEquals(1, savedNotifications.size) + assertEquals(1, captor.value.size) + assertEquals(10L, captor.value.single().teacherUserId) + } + + @Test + fun `resolve thread marks matching notifications as resolved`() { + val unresolvedFirst = TeacherNotification( + id = 1L, + teacherUserId = 10L, + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "stuck-1", + threadKey = "stuck:42:7:3", + title = "Elev star fast", + message = "En elev trenger hjelp.", + ) + val unresolvedSecond = TeacherNotification( + id = 2L, + teacherUserId = 11L, + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "stuck-2", + threadKey = "stuck:42:7:3", + title = "Elev star fast", + message = "En elev trenger hjelp.", + ) + `when`( + teacherNotificationRepository.findAllByClassroomIdAndThreadKeyAndResolvedAtIsNull( + 42L, + "stuck:42:7:3", + ), + ).thenReturn(listOf(unresolvedFirst, unresolvedSecond)) + `when`(teacherNotificationRepository.saveAll(anyList())).thenAnswer { it.arguments[0] } + + val resolvedCount = notificationDeliveryService.resolveThread(42L, "stuck:42:7:3") + + verify(teacherNotificationRepository, times(1)).saveAll(anyList()) + assertEquals(2, resolvedCount) + assertEquals(listOf(unresolvedFirst, unresolvedSecond).all { it.resolvedAt != null }, true) + } +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt new file mode 100644 index 00000000..dfa9de63 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt @@ -0,0 +1,107 @@ +package edu.ntnu.idi.idatt.backend.notification + +import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.domain.UserRole +import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import edu.ntnu.idi.idatt.backend.notification.application.NotificationInboxService +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.ArgumentMatchers.any +import org.mockito.Mockito.mock +import org.mockito.Mockito.times +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` + +class NotificationInboxServiceTests { + private lateinit var teacherNotificationRepository: TeacherNotificationRepository + private lateinit var currentUserResolver: CurrentUserResolver + private lateinit var notificationInboxService: NotificationInboxService + + @BeforeEach + fun setUp() { + teacherNotificationRepository = mock(TeacherNotificationRepository::class.java) + currentUserResolver = mock(CurrentUserResolver::class.java) + notificationInboxService = NotificationInboxService( + teacherNotificationRepository = teacherNotificationRepository, + currentUserResolver = currentUserResolver, + ) + } + + @Test + fun `mark read is idempotent`() { + val teacher = teacher() + val notification = notification() + `when`(currentUserResolver.requireTeacherOrAdmin("10")).thenReturn(teacher) + `when`(teacherNotificationRepository.findByIdAndTeacherUserId(1L, 10L)).thenReturn(notification) + `when`(teacherNotificationRepository.save(any(TeacherNotification::class.java))).thenAnswer { it.arguments[0] } + + val firstRead = notificationInboxService.markRead("10", 1L) + val secondRead = notificationInboxService.markRead("10", 1L) + + assertNotNull(firstRead.readAt) + assertEquals(firstRead.readAt, secondRead.readAt) + verify(teacherNotificationRepository, times(2)).save(notification) + } + + @Test + fun `dismiss sets read and dismissed timestamps`() { + val teacher = teacher() + val notification = notification() + `when`(currentUserResolver.requireTeacherOrAdmin("10")).thenReturn(teacher) + `when`(teacherNotificationRepository.findByIdAndTeacherUserId(1L, 10L)).thenReturn(notification) + `when`(teacherNotificationRepository.save(any(TeacherNotification::class.java))).thenAnswer { it.arguments[0] } + + val dismissed = notificationInboxService.dismiss("10", 1L) + + assertNotNull(dismissed.readAt) + assertNotNull(dismissed.dismissedAt) + } + + @Test + fun `dismiss keeps existing read timestamp`() { + val teacher = teacher() + val notification = notification() + notification.readAt = java.time.Instant.now() + `when`(currentUserResolver.requireTeacherOrAdmin("10")).thenReturn(teacher) + `when`(teacherNotificationRepository.findByIdAndTeacherUserId(1L, 10L)).thenReturn(notification) + `when`(teacherNotificationRepository.save(any(TeacherNotification::class.java))).thenAnswer { it.arguments[0] } + + val dismissed = notificationInboxService.dismiss("10", 1L) + + assertNotNull(dismissed.readAt) + assertNotNull(dismissed.dismissedAt) + assertEquals(notification.readAt, dismissed.readAt) + assertNull(notification.resolvedAt) + } + + private fun teacher(): User = + User( + id = 10L, + email = "teacher@example.com", + passwordHash = "hash", + role = UserRole.TEACHER, + status = UserStatus.ACTIVE, + ) + + private fun notification(): TeacherNotification = + TeacherNotification( + id = 1L, + teacherUserId = 10L, + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "stuck-1", + threadKey = "stuck:42:7:3", + title = "Elev star fast", + message = "En elev trenger hjelp.", + ) +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt new file mode 100644 index 00000000..d07104e7 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt @@ -0,0 +1,194 @@ +package edu.ntnu.idi.idatt.backend.notification + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.domain.UserRole +import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.dao.DataIntegrityViolationException +import org.springframework.data.domain.PageRequest +import java.time.Instant +import java.util.concurrent.atomic.AtomicInteger + +@SpringBootTest +class NotificationPersistenceTests @Autowired constructor( + private val userRepository: UserRepository, + private val classroomRepository: ClassroomRepository, + private val teacherNotificationRepository: TeacherNotificationRepository, + private val teacherNotificationMuteRepository: TeacherNotificationMuteRepository, +) { + companion object { + private val sequence = AtomicInteger() + } + + @Test + fun `finds teacher inbox entries with filters`() { + val teacher = teacher() + val otherTeacher = teacher() + val classroom = classroom(teacher) + val otherClassroom = classroom(teacher) + + teacherNotificationRepository.saveAndFlush( + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.MAP_STOP_COMPLETED, + ), + ) + teacherNotificationRepository.saveAndFlush( + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.PUPIL_STUCK, + readAt = Instant.now(), + ), + ) + teacherNotificationRepository.saveAndFlush( + notification( + teacherUserId = requireNotNull(teacher.id), + classroomId = otherClassroom.id, + type = NotificationType.GAME_COMPLETED, + dismissedAt = Instant.now(), + ), + ) + teacherNotificationRepository.saveAndFlush( + notification( + teacherUserId = requireNotNull(otherTeacher.id), + classroomId = classroom.id, + type = NotificationType.MAP_STOP_COMPLETED, + ), + ) + + val allInbox = teacherNotificationRepository.findInboxPage( + teacherUserId = requireNotNull(teacher.id), + classroomId = null, + type = null, + unreadOnly = false, + pageable = PageRequest.of(0, 20), + ) + val unreadInbox = teacherNotificationRepository.findInboxPage( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.MAP_STOP_COMPLETED, + unreadOnly = true, + pageable = PageRequest.of(0, 20), + ) + + assertEquals(2, allInbox.totalElements) + assertEquals(1, unreadInbox.totalElements) + assertEquals(1, teacherNotificationRepository.countByTeacherUserIdAndReadAtIsNullAndDismissedAtIsNull(requireNotNull(teacher.id))) + } + + @Test + fun `persists notification payload and thread key`() { + val teacher = teacher() + val classroom = classroom(teacher) + + val saved = teacherNotificationRepository.saveAndFlush( + TeacherNotification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + pupilUserId = null, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "stop-progress:1:2:3", + threadKey = "stuck:1:2:3", + title = "Elev star fast", + message = "En elev trenger hjelp.", + payloadJson = """{"stopId":3}""", + ), + ) + + assertNotNull(saved.id) + assertEquals("stuck:1:2:3", saved.threadKey) + assertEquals("""{"stopId":3}""", saved.payloadJson) + } + + @Test + fun `enforces one mute per teacher classroom and type`() { + val teacher = teacher() + val classroom = classroom(teacher) + + teacherNotificationMuteRepository.saveAndFlush( + TeacherNotificationMute( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.PUPIL_STUCK, + ), + ) + + assertThrows { + teacherNotificationMuteRepository.saveAndFlush( + TeacherNotificationMute( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + type = NotificationType.PUPIL_STUCK, + ), + ) + } + } + + private fun notification( + teacherUserId: Long, + classroomId: Long, + type: NotificationType, + readAt: Instant? = null, + dismissedAt: Instant? = null, + ): TeacherNotification = + TeacherNotification( + teacherUserId = teacherUserId, + classroomId = classroomId, + pupilUserId = null, + type = type, + sourceKind = when (type) { + NotificationType.MAP_STOP_COMPLETED, NotificationType.PUPIL_STUCK -> NotificationSourceKind.MAP_STOP_PROGRESS + NotificationType.GAME_COMPLETED -> NotificationSourceKind.GAME_PROGRESS + NotificationType.WEEKLY_MYSTERY_SUBMITTED -> NotificationSourceKind.WEEKLY_MYSTERY_SUBMISSION + }, + sourceKey = "${type.name.lowercase()}-${sequence.incrementAndGet()}", + threadKey = null, + title = type.name, + message = "Notification for $type", + readAt = readAt, + dismissedAt = dismissedAt, + ) + + private fun teacher(): User = + sequence.incrementAndGet().let { suffix -> + userRepository.saveAndFlush( + User( + email = "notify-teacher-$suffix@example.com", + passwordHash = "hash", + role = UserRole.TEACHER, + status = UserStatus.ACTIVE, + ), + ) + } + + private fun classroom(ownerTeacher: User): Classroom = + sequence.incrementAndGet().let { suffix -> + classroomRepository.saveAndFlush( + Classroom( + ownerTeacherId = requireNotNull(ownerTeacher.id), + title = "Notify-$suffix", + description = "Notification classroom", + joinCode = "NTY$suffix", + status = ClassroomStatus.ACTIVE, + ), + ) + } +} From 8a37c6054f6858347395399558f990bbc9f63d83 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Wed, 22 Apr 2026 14:58:41 +0200 Subject: [PATCH 02/15] Publish progress notifications --- .../classroom/application/ClassroomService.kt | 8 +- .../application/PupilJoinedClassroomEvent.kt | 5 +- .../game/mapstops/api/MapStopApiMappings.kt | 8 +- .../api/PupilStopProgressController.kt | 19 + .../api/RecordStopAttemptOutcomeRequest.kt | 5 + .../PupilProgressSeedingEventListener.kt | 2 +- .../application/PupilStopProgressService.kt | 107 +++++- .../RecordStopAttemptOutcomeCommand.kt | 8 + .../game/mapstops/domain/PupilStopProgress.kt | 4 +- ..._wrong_attempts_to_pupil_stop_progress.sql | 5 + .../backend/classroom/ClassroomServiceTest.kt | 6 +- .../mapstops/PupilStopProgressServiceTests.kt | 132 ++++++- .../NotificationEventIntegrationTests.kt | 350 ++++++++++++++++++ 13 files changed, 629 insertions(+), 30 deletions(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt create mode 100644 src/main/resources/db/migration/V18__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index c746cad5..cb5e812f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -12,7 +12,7 @@ import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository import edu.ntnu.idi.idatt.backend.game.tasks.infrastructure.TaskRepository import edu.ntnu.idi.idatt.backend.iam.domain.UserRole -import org.springframework.context.ApplicationEventPublisher +import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -27,7 +27,7 @@ import java.util.* * @property userRepository repository for user access. * @property classroomUserResolver repository for classroom access. * @property pupilGameProgressRepository pupil repository for game progress. - * @property eventPublisher publisher for application events. + * @property domainEventPublisher publisher for application events. */ @Service class ClassroomService( @@ -37,7 +37,7 @@ class ClassroomService( private val classroomUserResolver: ClassroomUserResolver, private val pupilGameProgressRepository: PupilGameProgressRepository, private val taskRepository: TaskRepository, - private val eventPublisher: ApplicationEventPublisher, + private val domainEventPublisher: DomainEventPublisher, ) { /** @@ -138,7 +138,7 @@ class ClassroomService( classroom = classroom, ), ) - eventPublisher.publishEvent(PupilJoinedClassroomEvent(pupil = user, classroom = classroom)) + domainEventPublisher.publish(PupilJoinedClassroomEvent(pupil = user, classroom = classroom)) return JoinClassroomResult( classroomId = classroom.id, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt index 2d1001e8..4f67e8d7 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/PupilJoinedClassroomEvent.kt @@ -2,8 +2,11 @@ package edu.ntnu.idi.idatt.backend.classroom.application import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom import edu.ntnu.idi.idatt.backend.iam.domain.User +import edu.ntnu.idi.idatt.backend.shared.events.DomainEvent +import java.time.Instant data class PupilJoinedClassroomEvent( val pupil: User, val classroom: Classroom, -) \ No newline at end of file + override val occurredAt: Instant = Instant.now(), +) : DomainEvent diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt index 5ed90089..5dbc11b2 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt @@ -1,6 +1,7 @@ package edu.ntnu.idi.idatt.backend.game.mapstops.api import edu.ntnu.idi.idatt.backend.game.mapstops.application.MapStopOverviewEntry +import edu.ntnu.idi.idatt.backend.game.mapstops.application.RecordStopAttemptOutcomeCommand import edu.ntnu.idi.idatt.backend.game.mapstops.application.UpdateStopProgressCommand import edu.ntnu.idi.idatt.backend.game.mapstops.domain.PupilStopProgress @@ -31,6 +32,11 @@ fun UpdateStopProgressRequest.toCommand(): UpdateStopProgressCommand = medalAwarded = medalAwarded, ) +fun RecordStopAttemptOutcomeRequest.toCommand(): RecordStopAttemptOutcomeCommand = + RecordStopAttemptOutcomeCommand( + correct = correct, + ) + /** * Converts a [MapStopOverviewEntry] application result to the public [MapStopOverviewResponse] * payload. @@ -46,4 +52,4 @@ fun MapStopOverviewEntry.toResponse(): MapStopOverviewResponse = status = status, stars = stars, medalAwarded = medalAwarded, - ) \ No newline at end of file + ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt index 9fc5a1ee..391be96b 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt @@ -11,6 +11,7 @@ import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PatchMapping import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @@ -102,4 +103,22 @@ class PupilStopProgressController( .updateProgress(pupilUserId, classroomId, stopId, request.toCommand()) .toStopProgressResponse() } + + /** + * Records one answer outcome for a stop. Only the pupil themselves may submit outcomes. + */ + @PostMapping("/{stopId}/attempt-outcomes") + @PreAuthorize("hasRole('PUPIL') and #pupilUserId == T(java.lang.Long).parseLong(authentication.principal.subject)") + fun recordAttemptOutcome( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable classroomId: Long, + @PathVariable pupilUserId: Long, + @PathVariable stopId: Long, + @Valid @RequestBody request: RecordStopAttemptOutcomeRequest, + ): StopProgressResponse { + currentUserResolver.requirePupil(currentUser.subject) + return progressService + .recordAttemptOutcome(pupilUserId, classroomId, stopId, request.toCommand()) + .toStopProgressResponse() + } } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt new file mode 100644 index 00000000..8409661c --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt @@ -0,0 +1,5 @@ +package edu.ntnu.idi.idatt.backend.game.mapstops.api + +data class RecordStopAttemptOutcomeRequest( + val correct: Boolean, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilProgressSeedingEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilProgressSeedingEventListener.kt index ff736518..d38dd1eb 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilProgressSeedingEventListener.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilProgressSeedingEventListener.kt @@ -26,4 +26,4 @@ class PupilProgressSeedingEventListener( classroom = event.classroom, ) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt index 5c844634..4a607247 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt @@ -5,6 +5,11 @@ import edu.ntnu.idi.idatt.backend.game.mapstops.domain.PupilStopProgress import edu.ntnu.idi.idatt.backend.game.mapstops.domain.StopProgressStatus import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgressRepository +import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher +import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -19,8 +24,13 @@ import java.time.Instant @Service class PupilStopProgressService( private val progressRepository: PupilStopProgressRepository, - private val mapStopRepository: MapStopsRepository + private val mapStopRepository: MapStopsRepository, + private val domainEventPublisher: DomainEventPublisher, ) { + companion object { + const val STUCK_ATTEMPT_THRESHOLD = 5 + } + /** * Returns all stop progress records for a pupil in a classroom. * @@ -87,7 +97,10 @@ class PupilStopProgressService( progress.status = next if (next == StopProgressStatus.COMPLETED && progress.completedAt == null) { + recoverFromStuckIfNeeded(progress) + progress.consecutiveWrongAttempts = 0 progress.completedAt = Instant.now() + publishCompletionEvents(progress) unlockNextStop(pupilUserId, classroomId, stopId, activeStops) } } @@ -98,6 +111,96 @@ class PupilStopProgressService( return progressRepository.save(progress) } + @Transactional + fun recordAttemptOutcome( + pupilUserId: Long, + classroomId: Long, + stopId: Long, + command: RecordStopAttemptOutcomeCommand, + ): PupilStopProgress { + val progress = getProgressForStop(pupilUserId, classroomId, stopId) + when (progress.status) { + StopProgressStatus.LOCKED -> throw ResponseStatusException( + HttpStatus.FORBIDDEN, + "Locked stops cannot record attempts", + ) + + StopProgressStatus.COMPLETED -> throw ResponseStatusException( + HttpStatus.UNPROCESSABLE_ENTITY, + "Completed stops cannot record attempts", + ) + + StopProgressStatus.NOT_STARTED -> progress.status = StopProgressStatus.IN_PROGRESS + StopProgressStatus.IN_PROGRESS -> Unit + } + + val wasStuck = progress.consecutiveWrongAttempts >= STUCK_ATTEMPT_THRESHOLD + if (command.correct) { + progress.consecutiveWrongAttempts = 0 + if (wasStuck) { + publishRecoveryEvent(progress) + } + } else { + progress.consecutiveWrongAttempts += 1 + if (!wasStuck && progress.consecutiveWrongAttempts >= STUCK_ATTEMPT_THRESHOLD) { + publishStuckEvent(progress) + } + } + + return progressRepository.save(progress) + } + + private fun publishCompletionEvents(progress: PupilStopProgress) { + val pupilUserId = requireNotNull(progress.id.pupilUserId) { "Progress is missing pupil id" } + val stopId = progress.id.stopId + val classroomId = progress.id.classroomId + domainEventPublisher.publish( + MapStopCompletedEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + ) + if (progress.stop.isFinalBoss == true && progress.stop.isActive == true) { + domainEventPublisher.publish( + PupilGameCompletedEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + ) + } + } + + private fun recoverFromStuckIfNeeded(progress: PupilStopProgress) { + if (progress.consecutiveWrongAttempts >= STUCK_ATTEMPT_THRESHOLD) { + publishRecoveryEvent(progress) + } + } + + private fun publishRecoveryEvent(progress: PupilStopProgress) { + val pupilUserId = requireNotNull(progress.id.pupilUserId) { "Progress is missing pupil id" } + domainEventPublisher.publish( + PupilRecoveredFromStuckEvent( + pupilUserId = pupilUserId, + classroomId = progress.id.classroomId, + stopId = progress.id.stopId, + ), + ) + } + + private fun publishStuckEvent(progress: PupilStopProgress) { + val pupilUserId = requireNotNull(progress.id.pupilUserId) { "Progress is missing pupil id" } + domainEventPublisher.publish( + PupilStuckThresholdReachedEvent( + pupilUserId = pupilUserId, + classroomId = progress.id.classroomId, + stopId = progress.id.stopId, + consecutiveWrongAttempts = progress.consecutiveWrongAttempts, + ), + ) + } + /** * Verifies that the stop preceding [stopId] in the active stop order is completed * for the given pupil in the given classroom, preventing pupils from skipping stops. @@ -183,4 +286,4 @@ class PupilStopProgressService( ) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt new file mode 100644 index 00000000..d90af2ae --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt @@ -0,0 +1,8 @@ +package edu.ntnu.idi.idatt.backend.game.mapstops.application + +/** + * Represents one recorded attempt outcome for a pupil on a stop. + */ +data class RecordStopAttemptOutcomeCommand( + val correct: Boolean, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/domain/PupilStopProgress.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/domain/PupilStopProgress.kt index d15f7cee..34b12d57 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/domain/PupilStopProgress.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/domain/PupilStopProgress.kt @@ -58,6 +58,8 @@ class PupilStopProgress( var currentTaskId: Long? = null @Column(nullable = false) var bestScore: Int = 0 + @Column(name = "consecutive_wrong_attempts", nullable = false) + var consecutiveWrongAttempts: Int = 0 @Column(nullable = false) var medalAwarded: Boolean = false @Column @@ -79,4 +81,4 @@ data class PupilStopProgressId( var classroomId: Long, @Column(name = "stop_id") var stopId: Long, -) : Serializable \ No newline at end of file +) : Serializable diff --git a/src/main/resources/db/migration/V18__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql b/src/main/resources/db/migration/V18__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql new file mode 100644 index 00000000..504935a6 --- /dev/null +++ b/src/main/resources/db/migration/V18__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql @@ -0,0 +1,5 @@ +ALTER TABLE pupil_stop_progress + ADD COLUMN consecutive_wrong_attempts INT NOT NULL DEFAULT 0; + +CREATE INDEX idx_psp_classroom_stop_status + ON pupil_stop_progress (classroom_id, stop_id, status); diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index ad73dd55..997b0565 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -19,6 +19,7 @@ import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach @@ -28,7 +29,6 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.Mockito.`when` -import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException import org.mockito.Mockito.any @@ -41,7 +41,7 @@ class ClassroomServiceTest { private lateinit var taskRepository: TaskRepository private lateinit var classroomService: ClassroomService private lateinit var userRepository: UserRepository - private lateinit var eventPublisher: ApplicationEventPublisher + private lateinit var eventPublisher: DomainEventPublisher @BeforeEach fun setup() { @@ -51,7 +51,7 @@ class ClassroomServiceTest { classroomUserResolver = mock(ClassroomUserResolver::class.java) pupilGameProgressRepository = mock(PupilGameProgressRepository::class.java) taskRepository = mock(TaskRepository::class.java) - eventPublisher = mock(ApplicationEventPublisher::class.java) + eventPublisher = mock(DomainEventPublisher::class.java) classroomService = ClassroomService( classroomRepository, currentUserResolver, 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..34ab1955 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 @@ -12,6 +12,11 @@ import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgress import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher +import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull @@ -28,7 +33,8 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns all progress records for given pupil and classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val records = listOf(progress(stopId = 1L), progress(stopId = 2L)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(records) @@ -42,7 +48,8 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns empty list when pupil has no records in classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(emptyList()) val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) @@ -54,7 +61,8 @@ class PupilStopProgressServiceTests { fun `get progress for stop returns record when it exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 3L) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 3L)) @@ -69,7 +77,8 @@ class PupilStopProgressServiceTests { fun `get progress for stop throws 404 when no record exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 99L)) .thenReturn(null) @@ -85,7 +94,8 @@ class PupilStopProgressServiceTests { fun `update progress transitions from LOCKED to NOT_STARTED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.LOCKED) stubFindAndSave(progressRepository, record) @@ -102,7 +112,8 @@ class PupilStopProgressServiceTests { fun `update progress transitions from NOT_STARTED to IN_PROGRESS`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFindAndSave(progressRepository, record) @@ -119,7 +130,8 @@ class PupilStopProgressServiceTests { fun `update progress transitions from IN_PROGRESS to COMPLETED and sets completedAt`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -131,13 +143,16 @@ class PupilStopProgressServiceTests { assertEquals(StopProgressStatus.COMPLETED, result.status) assertNotNull(result.completedAt) + val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } + assertEquals(true, publishedEvents.any { it is MapStopCompletedEvent }) } @Test fun `update progress does not overwrite completedAt when stop is already completed`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -158,7 +173,8 @@ class PupilStopProgressServiceTests { fun `update progress rejects invalid transition from COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.COMPLETED) stubFind(progressRepository, record) @@ -177,7 +193,8 @@ class PupilStopProgressServiceTests { fun `update progress rejects skipping from NOT_STARTED directly to COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFind(progressRepository, record) @@ -196,7 +213,8 @@ class PupilStopProgressServiceTests { fun `update progress persists higher best score`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, bestScore = 40) stubFindAndSave(progressRepository, record) @@ -213,7 +231,8 @@ class PupilStopProgressServiceTests { fun `update progress does not overwrite best score when new value is lower`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, bestScore = 90) stubFindAndSave(progressRepository, record) @@ -230,7 +249,8 @@ class PupilStopProgressServiceTests { fun `update progress sets current task id`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -247,7 +267,8 @@ class PupilStopProgressServiceTests { fun `update progress awards medal when medal flag is set`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -264,7 +285,8 @@ class PupilStopProgressServiceTests { fun `update progress with all null fields changes nothing`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, bestScore = 55) stubFindAndSave(progressRepository, record) @@ -279,10 +301,82 @@ class PupilStopProgressServiceTests { assertNull(result.completedAt) } + @Test + fun `update progress publishes game completed event for active final boss`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val record = progress(stopId = 99L, status = StopProgressStatus.IN_PROGRESS, isFinalBoss = true, isActive = true) + + stubFindAndSave(progressRepository, record) + + service.updateProgress( + pupilUserId = 1L, + classroomId = 2L, + stopId = 99L, + command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), + ) + + val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } + assertEquals(true, publishedEvents.any { it is MapStopCompletedEvent }) + assertEquals(true, publishedEvents.any { it is PupilGameCompletedEvent }) + } + + @Test + fun `record attempt outcome publishes stuck event at threshold only`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val record = progress(stopId = 3L, status = StopProgressStatus.IN_PROGRESS).apply { + consecutiveWrongAttempts = 4 + } + + stubFindAndSave(progressRepository, record) + + val result = service.recordAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 3L, + command = edu.ntnu.idi.idatt.backend.game.mapstops.application.RecordStopAttemptOutcomeCommand(correct = false), + ) + + val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } + assertEquals(5, result.consecutiveWrongAttempts) + assertEquals(true, publishedEvents.any { it is PupilStuckThresholdReachedEvent }) + } + + @Test + fun `record attempt outcome resets stuck counter and publishes recovery on correct answer`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val record = progress(stopId = 3L, status = StopProgressStatus.IN_PROGRESS).apply { + consecutiveWrongAttempts = 5 + } + + stubFindAndSave(progressRepository, record) + + val result = service.recordAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 3L, + command = edu.ntnu.idi.idatt.backend.game.mapstops.application.RecordStopAttemptOutcomeCommand(correct = true), + ) + + val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } + assertEquals(0, result.consecutiveWrongAttempts) + assertEquals(true, publishedEvents.any { it is PupilRecoveredFromStuckEvent }) + } + private fun progress( stopId: Long, status: StopProgressStatus = StopProgressStatus.NOT_STARTED, bestScore: Int = 0, + isFinalBoss: Boolean = false, + isActive: Boolean = true, ): PupilStopProgress { val pupil = User( id = 1L, @@ -291,7 +385,11 @@ class PupilStopProgressServiceTests { role = UserRole.PUPIL, status = UserStatus.ACTIVE, ) - val stop = MapStop().apply { id = stopId } + val stop = MapStop().apply { + id = stopId + this.isFinalBoss = isFinalBoss + this.isActive = isActive + } val classroom = Classroom(ownerTeacherId = 1L, title = "Test Classroom") return PupilStopProgress( id = PupilStopProgressId(pupilUserId = 1L, classroomId = 2L, stopId = stopId), @@ -314,4 +412,4 @@ class PupilStopProgressServiceTests { stubFind(repo, record) Mockito.`when`(repo.save(any(PupilStopProgress::class.java))).thenAnswer { it.arguments[0] } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt new file mode 100644 index 00000000..6877fbf4 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt @@ -0,0 +1,350 @@ +package edu.ntnu.idi.idatt.backend.notification + +import com.fasterxml.jackson.databind.json.JsonMapper +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus +import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository +import edu.ntnu.idi.idatt.backend.game.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.iam.domain.User +import edu.ntnu.idi.idatt.backend.iam.domain.UserRole +import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import edu.ntnu.idi.idatt.backend.iam.infrastructure.RefreshTokenRepository +import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository +import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.security.crypto.password.PasswordEncoder +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf +import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.patch +import org.springframework.test.web.servlet.post + +@SpringBootTest +@AutoConfigureMockMvc +class NotificationEventIntegrationTests { + @Autowired + private lateinit var mockMvc: MockMvc + + @Autowired + private lateinit var userRepository: UserRepository + + @Autowired + private lateinit var classroomRepository: ClassroomRepository + + @Autowired + private lateinit var mapStopsRepository: MapStopsRepository + + @Autowired + private lateinit var pupilStopProgressRepository: PupilStopProgressRepository + + @Autowired + private lateinit var teacherNotificationRepository: TeacherNotificationRepository + + @Autowired + private lateinit var teacherNotificationMuteRepository: TeacherNotificationMuteRepository + + @Autowired + private lateinit var refreshTokenRepository: RefreshTokenRepository + + @Autowired + private lateinit var passwordEncoder: PasswordEncoder + + private val jsonMapper = JsonMapper.builder().build() + + @BeforeEach + fun setUp() { + refreshTokenRepository.deleteAll() + teacherNotificationMuteRepository.deleteAll() + teacherNotificationRepository.deleteAll() + pupilStopProgressRepository.deleteAll() + mapStopsRepository.deleteAll() + classroomRepository.deleteAll() + userRepository.deleteAll() + } + + @Test + fun `stop completion creates one notification and repeated completion does not duplicate`() { + val teacher = userRepository.save(activeTeacher("owner-stop-event@example.com")) + val pupil = userRepository.save(activePupil("pupil-stop-event")) + val classroom = createClassroom("EVENTSTOP1", teacher) + val stop = createStop("event-stop-1", "Omrade 1", 1) + seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) + val pupilToken = pupilAccessToken("pupil-stop-event", "secret123") + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") + content = """{"status":"COMPLETED"}""" + }.andExpect { + status { isOk() } + } + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") + content = """{"status":"COMPLETED"}""" + }.andExpect { + status { isUnprocessableContent() } + } + + val notifications = awaitNotifications( + predicate = { it.size == 1 }, + ) { + teacherNotificationRepository.findAll() + .filter { it.teacherUserId == teacher.id && it.type == NotificationType.MAP_STOP_COMPLETED } + } + assertEquals(1, notifications.size) + } + + @Test + fun `final boss completion creates game completed notification`() { + val teacher = userRepository.save(activeTeacher("owner-game-event@example.com")) + val pupil = userRepository.save(activePupil("pupil-game-event")) + val classroom = createClassroom("EVENTGAME1", teacher) + val stop = createStop("event-final-boss", "Siste boss", 1, isFinalBoss = true) + seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) + val pupilToken = pupilAccessToken("pupil-game-event", "secret123") + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") + content = """{"status":"COMPLETED"}""" + }.andExpect { + status { isOk() } + } + + val notifications = awaitNotifications( + predicate = { + it.count { notification -> notification.type == NotificationType.MAP_STOP_COMPLETED } == 1 && + it.count { notification -> notification.type == NotificationType.GAME_COMPLETED } == 1 + }, + ) { + teacherNotificationRepository.findAll().filter { it.teacherUserId == teacher.id } + } + assertEquals(1, notifications.count { it.type == NotificationType.MAP_STOP_COMPLETED }) + assertEquals(1, notifications.count { it.type == NotificationType.GAME_COMPLETED }) + } + + @Test + fun `stuck notification appears on fifth wrong attempt`() { + val teacher = userRepository.save(activeTeacher("owner-stuck-event@example.com")) + val pupil = userRepository.save(activePupil("pupil-stuck-event")) + val classroom = createClassroom("EVENTSTUCK1", teacher) + val stop = createStop("event-stuck-stop", "Stuck stop", 1) + seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) + val pupilToken = pupilAccessToken("pupil-stuck-event", "secret123") + + repeat(4) { + wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) + } + assertEquals( + 0, + teacherNotificationRepository.findAll().count { + it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK + }, + ) + + wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) + + val stuckNotifications = awaitNotifications( + predicate = { it.size == 1 }, + ) { + teacherNotificationRepository.findAll() + .filter { it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK } + } + assertEquals(1, stuckNotifications.size) + assertEquals(null, stuckNotifications.single().resolvedAt) + } + + @Test + fun `correct answer resolves stuck notification and later threshold creates a new one`() { + val teacher = userRepository.save(activeTeacher("owner-recover-event@example.com")) + val pupil = userRepository.save(activePupil("pupil-recover-event")) + val classroom = createClassroom("EVENTRECOVER1", teacher) + val stop = createStop("event-recover-stop", "Recover stop", 1) + seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) + val pupilToken = pupilAccessToken("pupil-recover-event", "secret123") + + repeat(5) { + wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) + } + + mockMvc.post("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}/attempt-outcomes") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") + content = """{"correct":true}""" + }.andExpect { + status { isOk() } + } + + repeat(5) { + wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) + } + + val stuckNotifications = awaitNotifications( + predicate = { notifications -> + notifications.size == 2 && + notifications.first().resolvedAt != null && + notifications.last().resolvedAt == null + }, + ) { + teacherNotificationRepository.findAll() + .filter { it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK } + .sortedBy { it.createdAt } + } + assertEquals(2, stuckNotifications.size) + assertNotNull(stuckNotifications.first().resolvedAt) + assertEquals(null, stuckNotifications.last().resolvedAt) + } + + @Test + fun `stop completion resolves active stuck notification`() { + val teacher = userRepository.save(activeTeacher("owner-resolve-event@example.com")) + val pupil = userRepository.save(activePupil("pupil-resolve-event")) + val classroom = createClassroom("EVENTRESOLVE1", teacher) + val stop = createStop("event-resolve-stop", "Resolve stop", 1) + seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) + val pupilToken = pupilAccessToken("pupil-resolve-event", "secret123") + + repeat(5) { + wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) + } + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") + content = """{"status":"COMPLETED"}""" + }.andExpect { + status { isOk() } + } + + val stuckNotification = awaitNotifications( + predicate = { notifications -> notifications.size == 1 && notifications.single().resolvedAt != null }, + ) { + teacherNotificationRepository.findAll() + .filter { it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK } + }.single() + assertNotNull(stuckNotification.resolvedAt) + } + + private fun wrongAttempt(classroomId: Long, pupilUserId: Long, stopId: Long, token: String) { + mockMvc.post("/api/v1/classrooms/$classroomId/pupils/$pupilUserId/stop-progress/$stopId/attempt-outcomes") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $token") + content = """{"correct":false}""" + }.andExpect { + status { isOk() } + } + } + + private fun awaitNotifications( + timeoutMillis: Long = 1_500, + predicate: (List) -> Boolean = { it.isNotEmpty() }, + supplier: () -> List, + ): List { + val deadline = System.currentTimeMillis() + timeoutMillis + var notifications = supplier() + while (!predicate(notifications) && System.currentTimeMillis() < deadline) { + Thread.sleep(50) + notifications = supplier() + } + return notifications + } + + private fun createClassroom(code: String, owner: User): Classroom = + classroomRepository.saveAndFlush( + Classroom( + ownerTeacherId = requireNotNull(owner.id), + title = "Class $code", + description = "Event notification classroom", + joinCode = code, + status = ClassroomStatus.ACTIVE, + ), + ) + + private fun createStop(slug: String, title: String, displayOrder: Int, isFinalBoss: Boolean = false): MapStop = + mapStopsRepository.saveAndFlush( + MapStop( + slug = slug, + title = title, + displayOrder = displayOrder, + isFinalBoss = isFinalBoss, + isActive = true, + ), + ) + + private fun seedProgress(pupil: User, classroom: Classroom, stop: MapStop, status: StopProgressStatus) { + pupilStopProgressRepository.saveAndFlush( + PupilStopProgress( + id = PupilStopProgressId( + pupilUserId = requireNotNull(pupil.id), + classroomId = classroom.id, + stopId = requireNotNull(stop.id), + ), + pupil = pupil, + classroom = classroom, + stop = stop, + ).apply { + this.status = status + }, + ) + } + + private fun teacherAccessToken(email: String, password: String): String = + jsonMapper.readTree( + mockMvc.post("/api/v1/auth/teacher/login") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + content = """{"email":"$email","password":"$password"}""" + }.andExpect { + status { isOk() } + }.andReturn().response.contentAsString, + ).get("accessToken").asText() + + private fun pupilAccessToken(username: String, password: String): String = + jsonMapper.readTree( + mockMvc.post("/api/v1/auth/pupil/login") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + content = """{"username":"$username","password":"$password"}""" + }.andExpect { + status { isOk() } + }.andReturn().response.contentAsString, + ).get("accessToken").asText() + + private fun activeTeacher(email: String): User = + User( + email = email, + passwordHash = requireNotNull(passwordEncoder.encode("secret123")), + role = UserRole.TEACHER, + status = UserStatus.ACTIVE, + ) + + private fun activePupil(username: String): User = + User( + username = username, + passwordHash = requireNotNull(passwordEncoder.encode("secret123")), + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) +} From dc52eb5d14f64b6e082cc650baf71275797ddf6f Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Wed, 22 Apr 2026 15:09:23 +0200 Subject: [PATCH 03/15] Clean up notification event handling --- .../idatt/backend/classroom/application/ClassroomService.kt | 4 ---- .../application/TeacherNotificationEventListener.kt | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index cb5e812f..b86e1f45 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -111,10 +111,6 @@ class ClassroomService( val user = currentUserResolver.requirePupil(command.authenticatedSubject) val userId = requireNotNull(user.id) { "Authenticated user is missing an id" } - println("JOIN CLASSROOM REQUEST") - println("code = ${command.classroomCode}") - println("user = ${command.authenticatedSubject}") - val classroom = classroomRepository.findByJoinCode(normalizedClassroomCode) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt index e3986678..b8f22365 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt @@ -10,7 +10,7 @@ import org.springframework.context.event.EventListener import org.springframework.stereotype.Component /** - * Translates business events into teacher inbox notifications after commit. + * Translates business events into teacher inbox notifications. */ @Component class TeacherNotificationEventListener( From 6be4f2255b68a93e9359474b7ecce6eee61acc20 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Wed, 22 Apr 2026 15:09:51 +0200 Subject: [PATCH 04/15] Document notification architecture --- docs/notifications-architecture.md | 142 +++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 docs/notifications-architecture.md diff --git a/docs/notifications-architecture.md b/docs/notifications-architecture.md new file mode 100644 index 00000000..dfea3433 --- /dev/null +++ b/docs/notifications-architecture.md @@ -0,0 +1,142 @@ +# Notifications Architecture + +## Goal + +Teacher notifications are implemented as a dedicated backend module with one job: +turn typed business events into per-teacher inbox items. + +Source services do not talk to notification repositories directly. They only +publish domain events through `DomainEventPublisher`. + +## Current event flow + +1. A source service completes a business action. +2. The source service publishes a typed event from `shared/events`. +3. A listener in `notification/application` translates that event into a + `NotificationDraft`. +4. `NotificationDeliveryService` fans the draft out to all teacher recipients + for the classroom, excluding muted recipients and duplicate active threads. +5. One `TeacherNotification` row is stored per teacher recipient. + +This is intentionally an internal in-process event system. It keeps usage simple +for existing services and can later be replaced with a different transport if +the product grows beyond one backend instance. + +## Module responsibilities + +- `shared/events` + Source-side contracts and the shared `DomainEventPublisher` abstraction. +- `notification/domain` + Notification entities and enums. +- `notification/application` + Delivery, inbox, mute handling, recipient resolution, and event listeners. +- `notification/api` + Teacher inbox and mute endpoints. +- `notification/infrastructure` + JPA repositories. + +## Persistence model + +### `teacher_notifications` + +Each row is one inbox item for one teacher. + +Important fields: + +- `teacher_user_id` +- `classroom_id` +- `pupil_user_id` +- `type` +- `source_kind` +- `source_key` +- `thread_key` +- `title` +- `message` +- `payload_json` +- `read_at` +- `dismissed_at` +- `resolved_at` + +This keeps read, dismiss, and mute state personal to each teacher. + +### `teacher_notification_mutes` + +Mute scope is: + +- teacher +- classroom +- notification type + +Muting suppresses new deliveries only. Existing inbox items remain visible until +they are dismissed. + +## Supported notification types + +Currently implemented producers: + +- `MAP_STOP_COMPLETED` +- `GAME_COMPLETED` +- `PUPIL_STUCK` + +Reserved extension point: + +- `WEEKLY_MYSTERY_SUBMITTED` + +`ContentFlaggedEvent` is intentionally not part of this system. Notebook entries +are now handled by teacher deletion instead of a teacher flagging workflow. + +## Stuck pupil contract + +`PupilStopProgress` stores `consecutiveWrongAttempts`. + +Rules: + +- wrong answer increments the counter +- correct answer resets the counter +- stop completion resets the counter +- crossing `4 -> 5` publishes `PupilStuckThresholdReachedEvent` +- recovering from a stuck state publishes `PupilRecoveredFromStuckEvent` + +Recovery resolves the active stuck notification thread by setting +`resolved_at`. + +## Threading and deduplication + +Notifications that represent an active state use `thread_key`. + +Current keys: + +- `stop-completed:{classroomId}:{pupilUserId}:{stopId}` +- `game-completed:{classroomId}:{pupilUserId}` +- `stuck:{classroomId}:{pupilUserId}:{stopId}` + +`NotificationDeliveryService` avoids creating another active notification for +the same teacher and thread while an unresolved row already exists. + +## API surface + +Teacher inbox endpoints: + +- `GET /api/v1/users/me/notifications` +- `GET /api/v1/users/me/notifications/summary` +- `PATCH /api/v1/users/me/notifications/{id}/read` +- `PATCH /api/v1/users/me/notifications/{id}/dismiss` +- `GET /api/v1/users/me/notifications/mutes` +- `PUT /api/v1/users/me/notifications/mutes/{classroomId}/{type}` +- `DELETE /api/v1/users/me/notifications/mutes/{classroomId}/{type}` + +These endpoints operate on the authenticated teacher's personal inbox rows only. + +## How to add a new notification producer + +1. Add a typed business event in `shared/events`. +2. Publish it from the source service through `DomainEventPublisher`. +3. Add a listener method in `TeacherNotificationEventListener`. +4. Build a `NotificationDraft` there, including a stable `sourceKey` and, if + needed, a `threadKey`. +5. Reuse `NotificationSourceKind` and `NotificationType` if possible. Add new + enum values only when the business concept is genuinely new. +6. Add or update integration tests proving one notification per unmuted teacher + recipient and correct deduplication behavior. + +Do not call notification repositories from source services. From b962183d4c4c8dfe41de1bee380d1975a1b03fc7 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 09:48:39 +0200 Subject: [PATCH 05/15] Improve notification delivery by preventing duplicate active threads --- docs/notifications-architecture.md | 30 ++- .../game/mapstops/api/MapStopApiMappings.kt | 6 - .../api/PupilStopProgressController.kt | 19 -- .../api/RecordStopAttemptOutcomeRequest.kt | 5 - .../application/PupilStopProgressService.kt | 103 ---------- .../RecordStopAttemptOutcomeCommand.kt | 8 - .../NotificationDeliveryService.kt | 65 ++++--- .../domain/TeacherNotification.kt | 2 + ...16__create_teacher_notifications_table.sql | 5 +- .../mapstops/PupilStopProgressServiceTests.kt | 110 ++--------- .../NotificationDeliveryServiceTests.kt | 29 +-- .../NotificationEventIntegrationTests.kt | 176 +----------------- .../NotificationPersistenceTests.kt | 41 ++++ 13 files changed, 138 insertions(+), 461 deletions(-) delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt diff --git a/docs/notifications-architecture.md b/docs/notifications-architecture.md index dfea3433..51c2d5cb 100644 --- a/docs/notifications-architecture.md +++ b/docs/notifications-architecture.md @@ -50,6 +50,7 @@ Important fields: - `source_kind` - `source_key` - `thread_key` +- `active_thread_key` - `title` - `message` - `payload_json` @@ -72,11 +73,13 @@ they are dismissed. ## Supported notification types -Currently implemented producers: +Currently wired producers: -- `MAP_STOP_COMPLETED` -- `GAME_COMPLETED` -- `PUPIL_STUCK` +- none yet for pupil gameplay progress + +The notification types for progress events already exist in the model, but they +must only be published from a server-verified gameplay flow. They are not +currently triggered from pupil-controlled progress endpoints. Reserved extension point: @@ -87,18 +90,8 @@ are now handled by teacher deletion instead of a teacher flagging workflow. ## Stuck pupil contract -`PupilStopProgress` stores `consecutiveWrongAttempts`. - -Rules: - -- wrong answer increments the counter -- correct answer resets the counter -- stop completion resets the counter -- crossing `4 -> 5` publishes `PupilStuckThresholdReachedEvent` -- recovering from a stuck state publishes `PupilRecoveredFromStuckEvent` - -Recovery resolves the active stuck notification thread by setting -`resolved_at`. +`PupilStopProgress` stores `consecutiveWrongAttempts` as a backend-owned signal +reserved for future verified gameplay integration. ## Threading and deduplication @@ -110,8 +103,9 @@ Current keys: - `game-completed:{classroomId}:{pupilUserId}` - `stuck:{classroomId}:{pupilUserId}:{stopId}` -`NotificationDeliveryService` avoids creating another active notification for -the same teacher and thread while an unresolved row already exists. +`active_thread_key` is set while a thread is unresolved and cleared on +resolution. A unique database constraint on `(teacher_user_id, active_thread_key)` +prevents concurrent duplicate deliveries for the same active thread. ## API surface diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt index 5dbc11b2..84ed15a9 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/MapStopApiMappings.kt @@ -1,7 +1,6 @@ package edu.ntnu.idi.idatt.backend.game.mapstops.api import edu.ntnu.idi.idatt.backend.game.mapstops.application.MapStopOverviewEntry -import edu.ntnu.idi.idatt.backend.game.mapstops.application.RecordStopAttemptOutcomeCommand import edu.ntnu.idi.idatt.backend.game.mapstops.application.UpdateStopProgressCommand import edu.ntnu.idi.idatt.backend.game.mapstops.domain.PupilStopProgress @@ -32,11 +31,6 @@ fun UpdateStopProgressRequest.toCommand(): UpdateStopProgressCommand = medalAwarded = medalAwarded, ) -fun RecordStopAttemptOutcomeRequest.toCommand(): RecordStopAttemptOutcomeCommand = - RecordStopAttemptOutcomeCommand( - correct = correct, - ) - /** * Converts a [MapStopOverviewEntry] application result to the public [MapStopOverviewResponse] * payload. diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt index 391be96b..9fc5a1ee 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/PupilStopProgressController.kt @@ -11,7 +11,6 @@ import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PatchMapping import org.springframework.web.bind.annotation.PathVariable -import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @@ -103,22 +102,4 @@ class PupilStopProgressController( .updateProgress(pupilUserId, classroomId, stopId, request.toCommand()) .toStopProgressResponse() } - - /** - * Records one answer outcome for a stop. Only the pupil themselves may submit outcomes. - */ - @PostMapping("/{stopId}/attempt-outcomes") - @PreAuthorize("hasRole('PUPIL') and #pupilUserId == T(java.lang.Long).parseLong(authentication.principal.subject)") - fun recordAttemptOutcome( - @AuthenticationPrincipal currentUser: CurrentUser, - @PathVariable classroomId: Long, - @PathVariable pupilUserId: Long, - @PathVariable stopId: Long, - @Valid @RequestBody request: RecordStopAttemptOutcomeRequest, - ): StopProgressResponse { - currentUserResolver.requirePupil(currentUser.subject) - return progressService - .recordAttemptOutcome(pupilUserId, classroomId, stopId, request.toCommand()) - .toStopProgressResponse() - } } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt deleted file mode 100644 index 8409661c..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/api/RecordStopAttemptOutcomeRequest.kt +++ /dev/null @@ -1,5 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapstops.api - -data class RecordStopAttemptOutcomeRequest( - val correct: Boolean, -) 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 4a607247..59d1a99a 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt @@ -5,11 +5,6 @@ import edu.ntnu.idi.idatt.backend.game.mapstops.domain.PupilStopProgress import edu.ntnu.idi.idatt.backend.game.mapstops.domain.StopProgressStatus import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgressRepository -import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher -import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent -import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent -import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent -import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -25,12 +20,7 @@ import java.time.Instant class PupilStopProgressService( private val progressRepository: PupilStopProgressRepository, private val mapStopRepository: MapStopsRepository, - private val domainEventPublisher: DomainEventPublisher, ) { - companion object { - const val STUCK_ATTEMPT_THRESHOLD = 5 - } - /** * Returns all stop progress records for a pupil in a classroom. * @@ -97,10 +87,7 @@ class PupilStopProgressService( progress.status = next if (next == StopProgressStatus.COMPLETED && progress.completedAt == null) { - recoverFromStuckIfNeeded(progress) - progress.consecutiveWrongAttempts = 0 progress.completedAt = Instant.now() - publishCompletionEvents(progress) unlockNextStop(pupilUserId, classroomId, stopId, activeStops) } } @@ -111,96 +98,6 @@ class PupilStopProgressService( return progressRepository.save(progress) } - @Transactional - fun recordAttemptOutcome( - pupilUserId: Long, - classroomId: Long, - stopId: Long, - command: RecordStopAttemptOutcomeCommand, - ): PupilStopProgress { - val progress = getProgressForStop(pupilUserId, classroomId, stopId) - when (progress.status) { - StopProgressStatus.LOCKED -> throw ResponseStatusException( - HttpStatus.FORBIDDEN, - "Locked stops cannot record attempts", - ) - - StopProgressStatus.COMPLETED -> throw ResponseStatusException( - HttpStatus.UNPROCESSABLE_ENTITY, - "Completed stops cannot record attempts", - ) - - StopProgressStatus.NOT_STARTED -> progress.status = StopProgressStatus.IN_PROGRESS - StopProgressStatus.IN_PROGRESS -> Unit - } - - val wasStuck = progress.consecutiveWrongAttempts >= STUCK_ATTEMPT_THRESHOLD - if (command.correct) { - progress.consecutiveWrongAttempts = 0 - if (wasStuck) { - publishRecoveryEvent(progress) - } - } else { - progress.consecutiveWrongAttempts += 1 - if (!wasStuck && progress.consecutiveWrongAttempts >= STUCK_ATTEMPT_THRESHOLD) { - publishStuckEvent(progress) - } - } - - return progressRepository.save(progress) - } - - private fun publishCompletionEvents(progress: PupilStopProgress) { - val pupilUserId = requireNotNull(progress.id.pupilUserId) { "Progress is missing pupil id" } - val stopId = progress.id.stopId - val classroomId = progress.id.classroomId - domainEventPublisher.publish( - MapStopCompletedEvent( - pupilUserId = pupilUserId, - classroomId = classroomId, - stopId = stopId, - ), - ) - if (progress.stop.isFinalBoss == true && progress.stop.isActive == true) { - domainEventPublisher.publish( - PupilGameCompletedEvent( - pupilUserId = pupilUserId, - classroomId = classroomId, - stopId = stopId, - ), - ) - } - } - - private fun recoverFromStuckIfNeeded(progress: PupilStopProgress) { - if (progress.consecutiveWrongAttempts >= STUCK_ATTEMPT_THRESHOLD) { - publishRecoveryEvent(progress) - } - } - - private fun publishRecoveryEvent(progress: PupilStopProgress) { - val pupilUserId = requireNotNull(progress.id.pupilUserId) { "Progress is missing pupil id" } - domainEventPublisher.publish( - PupilRecoveredFromStuckEvent( - pupilUserId = pupilUserId, - classroomId = progress.id.classroomId, - stopId = progress.id.stopId, - ), - ) - } - - private fun publishStuckEvent(progress: PupilStopProgress) { - val pupilUserId = requireNotNull(progress.id.pupilUserId) { "Progress is missing pupil id" } - domainEventPublisher.publish( - PupilStuckThresholdReachedEvent( - pupilUserId = pupilUserId, - classroomId = progress.id.classroomId, - stopId = progress.id.stopId, - consecutiveWrongAttempts = progress.consecutiveWrongAttempts, - ), - ) - } - /** * Verifies that the stop preceding [stopId] in the active stop order is completed * for the given pupil in the given classroom, preventing pupils from skipping stops. diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt deleted file mode 100644 index d90af2ae..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/RecordStopAttemptOutcomeCommand.kt +++ /dev/null @@ -1,8 +0,0 @@ -package edu.ntnu.idi.idatt.backend.game.mapstops.application - -/** - * Represents one recorded attempt outcome for a pupil on a stop. - */ -data class RecordStopAttemptOutcomeCommand( - val correct: Boolean, -) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt index 54c0119e..96d999e1 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt @@ -3,6 +3,7 @@ package edu.ntnu.idi.idatt.backend.notification.application import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository +import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.Instant @@ -19,39 +20,46 @@ class NotificationDeliveryService( @Transactional fun deliverToClassroomTeachers(draft: NotificationDraft): List { val recipients = recipientResolver.resolveTeacherRecipientIds(draft.classroomId) + val notifications = mutableListOf() - val notifications = recipients - .filterNot { teacherUserId -> - teacherNotificationMuteRepository.existsByTeacherUserIdAndClassroomIdAndType( - teacherUserId = teacherUserId, - classroomId = draft.classroomId, - type = draft.type, - ) - } - .filterNot { teacherUserId -> - draft.threadKey != null && - teacherNotificationRepository.findActiveThreadNotifications(teacherUserId, draft.threadKey).isNotEmpty() - } - .map { teacherUserId -> - TeacherNotification( - teacherUserId = teacherUserId, - classroomId = draft.classroomId, - pupilUserId = draft.pupilUserId, - type = draft.type, - sourceKind = draft.sourceKind, - sourceKey = draft.sourceKey, - threadKey = draft.threadKey, - title = draft.title, - message = draft.message, - payloadJson = draft.payloadJson, - ) + recipients.forEach { teacherUserId -> + val isMuted = teacherNotificationMuteRepository.existsByTeacherUserIdAndClassroomIdAndType( + teacherUserId = teacherUserId, + classroomId = draft.classroomId, + type = draft.type, + ) + if (isMuted) { + return@forEach } - if (notifications.isEmpty()) { - return emptyList() + val notification = TeacherNotification( + teacherUserId = teacherUserId, + classroomId = draft.classroomId, + pupilUserId = draft.pupilUserId, + type = draft.type, + sourceKind = draft.sourceKind, + sourceKey = draft.sourceKey, + threadKey = draft.threadKey, + activeThreadKey = draft.threadKey, + title = draft.title, + message = draft.message, + payloadJson = draft.payloadJson, + ) + + try { + notifications += teacherNotificationRepository.saveAndFlush(notification) + } catch (exception: DataIntegrityViolationException) { + val threadKey = draft.threadKey + if (threadKey != null && + teacherNotificationRepository.findActiveThreadNotifications(teacherUserId, threadKey).isNotEmpty() + ) { + return@forEach + } + throw exception + } } - return teacherNotificationRepository.saveAll(notifications) + return notifications } @Transactional @@ -68,6 +76,7 @@ class NotificationDeliveryService( activeNotifications.forEach { notification -> notification.resolvedAt = now + notification.activeThreadKey = null } teacherNotificationRepository.saveAll(activeNotifications) return activeNotifications.size diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt index 8f338eb7..1ec90ed6 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt @@ -37,6 +37,8 @@ class TeacherNotification( var sourceKey: String, @Column(name = "thread_key", length = 255) var threadKey: String? = null, + @Column(name = "active_thread_key", length = 255) + var activeThreadKey: String? = null, @Column(nullable = false, length = 255) var title: String, @Column(nullable = false, columnDefinition = "TEXT") diff --git a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql index 134e0355..185a3b69 100644 --- a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql +++ b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql @@ -7,6 +7,7 @@ CREATE TABLE teacher_notifications ( source_kind ENUM('MAP_STOP_PROGRESS', 'GAME_PROGRESS', 'WEEKLY_MYSTERY_SUBMISSION') NOT NULL, source_key VARCHAR(255) NOT NULL, thread_key VARCHAR(255), + active_thread_key VARCHAR(255), title VARCHAR(255) NOT NULL, message TEXT NOT NULL, payload_json TEXT, @@ -21,7 +22,9 @@ CREATE TABLE teacher_notifications ( CONSTRAINT fk_teacher_notifications_classroom FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE, CONSTRAINT fk_teacher_notifications_pupil - FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE + FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT uk_teacher_notifications_active_thread + UNIQUE (teacher_user_id, active_thread_key) ); CREATE INDEX idx_teacher_notifications_teacher_created 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 34ab1955..8859649f 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 @@ -12,11 +12,6 @@ import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgress import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus -import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher -import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent -import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent -import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent -import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull @@ -33,8 +28,7 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns all progress records for given pupil and classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val records = listOf(progress(stopId = 1L), progress(stopId = 2L)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(records) @@ -48,8 +42,7 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns empty list when pupil has no records in classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(emptyList()) val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) @@ -61,8 +54,7 @@ class PupilStopProgressServiceTests { fun `get progress for stop returns record when it exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 3L) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 3L)) @@ -77,8 +69,7 @@ class PupilStopProgressServiceTests { fun `get progress for stop throws 404 when no record exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 99L)) .thenReturn(null) @@ -94,8 +85,7 @@ class PupilStopProgressServiceTests { fun `update progress transitions from LOCKED to NOT_STARTED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.LOCKED) stubFindAndSave(progressRepository, record) @@ -112,8 +102,7 @@ class PupilStopProgressServiceTests { fun `update progress transitions from NOT_STARTED to IN_PROGRESS`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFindAndSave(progressRepository, record) @@ -130,8 +119,7 @@ class PupilStopProgressServiceTests { fun `update progress transitions from IN_PROGRESS to COMPLETED and sets completedAt`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -143,16 +131,13 @@ class PupilStopProgressServiceTests { assertEquals(StopProgressStatus.COMPLETED, result.status) assertNotNull(result.completedAt) - val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } - assertEquals(true, publishedEvents.any { it is MapStopCompletedEvent }) } @Test fun `update progress does not overwrite completedAt when stop is already completed`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -173,8 +158,7 @@ class PupilStopProgressServiceTests { fun `update progress rejects invalid transition from COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.COMPLETED) stubFind(progressRepository, record) @@ -193,8 +177,7 @@ class PupilStopProgressServiceTests { fun `update progress rejects skipping from NOT_STARTED directly to COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFind(progressRepository, record) @@ -213,8 +196,7 @@ class PupilStopProgressServiceTests { fun `update progress persists higher best score`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, bestScore = 40) stubFindAndSave(progressRepository, record) @@ -231,8 +213,7 @@ class PupilStopProgressServiceTests { fun `update progress does not overwrite best score when new value is lower`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, bestScore = 90) stubFindAndSave(progressRepository, record) @@ -249,8 +230,7 @@ class PupilStopProgressServiceTests { fun `update progress sets current task id`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -267,8 +247,7 @@ class PupilStopProgressServiceTests { fun `update progress awards medal when medal flag is set`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -285,8 +264,7 @@ class PupilStopProgressServiceTests { fun `update progress with all null fields changes nothing`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, bestScore = 55) stubFindAndSave(progressRepository, record) @@ -302,11 +280,10 @@ class PupilStopProgressServiceTests { } @Test - fun `update progress publishes game completed event for active final boss`() { + fun `update progress completes active final boss without special side effects`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) + val service = PupilStopProgressService(progressRepository, mapStopRepository) val record = progress(stopId = 99L, status = StopProgressStatus.IN_PROGRESS, isFinalBoss = true, isActive = true) stubFindAndSave(progressRepository, record) @@ -318,57 +295,8 @@ class PupilStopProgressServiceTests { command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), ) - val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } - assertEquals(true, publishedEvents.any { it is MapStopCompletedEvent }) - assertEquals(true, publishedEvents.any { it is PupilGameCompletedEvent }) - } - - @Test - fun `record attempt outcome publishes stuck event at threshold only`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) - val record = progress(stopId = 3L, status = StopProgressStatus.IN_PROGRESS).apply { - consecutiveWrongAttempts = 4 - } - - stubFindAndSave(progressRepository, record) - - val result = service.recordAttemptOutcome( - pupilUserId = 1L, - classroomId = 2L, - stopId = 3L, - command = edu.ntnu.idi.idatt.backend.game.mapstops.application.RecordStopAttemptOutcomeCommand(correct = false), - ) - - val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } - assertEquals(5, result.consecutiveWrongAttempts) - assertEquals(true, publishedEvents.any { it is PupilStuckThresholdReachedEvent }) - } - - @Test - fun `record attempt outcome resets stuck counter and publishes recovery on correct answer`() { - val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) - val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val eventPublisher = Mockito.mock(DomainEventPublisher::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository, eventPublisher) - val record = progress(stopId = 3L, status = StopProgressStatus.IN_PROGRESS).apply { - consecutiveWrongAttempts = 5 - } - - stubFindAndSave(progressRepository, record) - - val result = service.recordAttemptOutcome( - pupilUserId = 1L, - classroomId = 2L, - stopId = 3L, - command = edu.ntnu.idi.idatt.backend.game.mapstops.application.RecordStopAttemptOutcomeCommand(correct = true), - ) - - val publishedEvents = Mockito.mockingDetails(eventPublisher).invocations.map { it.arguments.first() } - assertEquals(0, result.consecutiveWrongAttempts) - assertEquals(true, publishedEvents.any { it is PupilRecoveredFromStuckEvent }) + assertEquals(StopProgressStatus.COMPLETED, record.status) + assertNotNull(record.completedAt) } private fun progress( diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt index e6a7cc28..b1cd9c2c 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt @@ -9,9 +9,10 @@ import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import org.mockito.ArgumentCaptor +import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.anyList import org.mockito.Mockito.mock import org.mockito.Mockito.times @@ -38,7 +39,7 @@ class NotificationDeliveryServiceTests { } @Test - fun `deliver skips muted and already active thread recipients`() { + fun `deliver skips muted and duplicate active thread recipients`() { val draft = NotificationDraft( classroomId = 42L, pupilUserId = 7L, @@ -73,10 +74,14 @@ class NotificationDeliveryServiceTests { NotificationType.PUPIL_STUCK, ), ).thenReturn(false) - `when`(teacherNotificationRepository.findActiveThreadNotifications(10L, "stuck:42:7:3")).thenReturn(emptyList()) - `when`( - teacherNotificationRepository.findActiveThreadNotifications(12L, "stuck:42:7:3"), - ).thenReturn( + `when`(teacherNotificationRepository.saveAndFlush(any(TeacherNotification::class.java))).thenAnswer { invocation -> + val notification = invocation.arguments[0] as TeacherNotification + if (notification.teacherUserId == 12L) { + throw org.springframework.dao.DataIntegrityViolationException("duplicate active thread") + } + notification + } + `when`(teacherNotificationRepository.findActiveThreadNotifications(12L, "stuck:42:7:3")).thenReturn( listOf( TeacherNotification( teacherUserId = 12L, @@ -86,20 +91,18 @@ class NotificationDeliveryServiceTests { sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, sourceKey = "existing", threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", title = "Existing", message = "Existing", ), ), ) - `when`(teacherNotificationRepository.saveAll(anyList())).thenAnswer { it.arguments[0] } val savedNotifications = notificationDeliveryService.deliverToClassroomTeachers(draft) - val captor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor> - verify(teacherNotificationRepository).saveAll(captor.capture()) assertEquals(1, savedNotifications.size) - assertEquals(1, captor.value.size) - assertEquals(10L, captor.value.single().teacherUserId) + assertEquals(10L, savedNotifications.single().teacherUserId) + verify(teacherNotificationRepository, times(2)).saveAndFlush(any(TeacherNotification::class.java)) } @Test @@ -113,6 +116,7 @@ class NotificationDeliveryServiceTests { sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, sourceKey = "stuck-1", threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", title = "Elev star fast", message = "En elev trenger hjelp.", ) @@ -125,6 +129,7 @@ class NotificationDeliveryServiceTests { sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, sourceKey = "stuck-2", threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", title = "Elev star fast", message = "En elev trenger hjelp.", ) @@ -141,5 +146,7 @@ class NotificationDeliveryServiceTests { verify(teacherNotificationRepository, times(1)).saveAll(anyList()) assertEquals(2, resolvedCount) assertEquals(listOf(unresolvedFirst, unresolvedSecond).all { it.resolvedAt != null }, true) + assertNull(unresolvedFirst.activeThreadKey) + assertNull(unresolvedSecond.activeThreadKey) } } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt index 6877fbf4..36fe4f1c 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt @@ -15,11 +15,9 @@ 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.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired @@ -77,7 +75,7 @@ class NotificationEventIntegrationTests { } @Test - fun `stop completion creates one notification and repeated completion does not duplicate`() { + fun `client controlled stop completion does not create teacher notifications`() { val teacher = userRepository.save(activeTeacher("owner-stop-event@example.com")) val pupil = userRepository.save(activePupil("pupil-stop-event")) val classroom = createClassroom("EVENTSTOP1", teacher) @@ -94,56 +92,11 @@ class NotificationEventIntegrationTests { status { isOk() } } - mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { - with(csrf()) - contentType = MediaType.APPLICATION_JSON - header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") - content = """{"status":"COMPLETED"}""" - }.andExpect { - status { isUnprocessableContent() } - } - - val notifications = awaitNotifications( - predicate = { it.size == 1 }, - ) { - teacherNotificationRepository.findAll() - .filter { it.teacherUserId == teacher.id && it.type == NotificationType.MAP_STOP_COMPLETED } - } - assertEquals(1, notifications.size) + assertEquals(0, teacherNotificationRepository.count()) } @Test - fun `final boss completion creates game completed notification`() { - val teacher = userRepository.save(activeTeacher("owner-game-event@example.com")) - val pupil = userRepository.save(activePupil("pupil-game-event")) - val classroom = createClassroom("EVENTGAME1", teacher) - val stop = createStop("event-final-boss", "Siste boss", 1, isFinalBoss = true) - seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) - val pupilToken = pupilAccessToken("pupil-game-event", "secret123") - - mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { - with(csrf()) - contentType = MediaType.APPLICATION_JSON - header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") - content = """{"status":"COMPLETED"}""" - }.andExpect { - status { isOk() } - } - - val notifications = awaitNotifications( - predicate = { - it.count { notification -> notification.type == NotificationType.MAP_STOP_COMPLETED } == 1 && - it.count { notification -> notification.type == NotificationType.GAME_COMPLETED } == 1 - }, - ) { - teacherNotificationRepository.findAll().filter { it.teacherUserId == teacher.id } - } - assertEquals(1, notifications.count { it.type == NotificationType.MAP_STOP_COMPLETED }) - assertEquals(1, notifications.count { it.type == NotificationType.GAME_COMPLETED }) - } - - @Test - fun `stuck notification appears on fifth wrong attempt`() { + fun `attempt outcomes endpoint is not exposed to pupils`() { val teacher = userRepository.save(activeTeacher("owner-stuck-event@example.com")) val pupil = userRepository.save(activePupil("pupil-stuck-event")) val classroom = createClassroom("EVENTSTUCK1", teacher) @@ -151,124 +104,16 @@ class NotificationEventIntegrationTests { seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) val pupilToken = pupilAccessToken("pupil-stuck-event", "secret123") - repeat(4) { - wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) - } - assertEquals( - 0, - teacherNotificationRepository.findAll().count { - it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK - }, - ) - - wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) - - val stuckNotifications = awaitNotifications( - predicate = { it.size == 1 }, - ) { - teacherNotificationRepository.findAll() - .filter { it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK } - } - assertEquals(1, stuckNotifications.size) - assertEquals(null, stuckNotifications.single().resolvedAt) - } - - @Test - fun `correct answer resolves stuck notification and later threshold creates a new one`() { - val teacher = userRepository.save(activeTeacher("owner-recover-event@example.com")) - val pupil = userRepository.save(activePupil("pupil-recover-event")) - val classroom = createClassroom("EVENTRECOVER1", teacher) - val stop = createStop("event-recover-stop", "Recover stop", 1) - seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) - val pupilToken = pupilAccessToken("pupil-recover-event", "secret123") - - repeat(5) { - wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) - } - mockMvc.post("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}/attempt-outcomes") { with(csrf()) contentType = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") - content = """{"correct":true}""" - }.andExpect { - status { isOk() } - } - - repeat(5) { - wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) - } - - val stuckNotifications = awaitNotifications( - predicate = { notifications -> - notifications.size == 2 && - notifications.first().resolvedAt != null && - notifications.last().resolvedAt == null - }, - ) { - teacherNotificationRepository.findAll() - .filter { it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK } - .sortedBy { it.createdAt } - } - assertEquals(2, stuckNotifications.size) - assertNotNull(stuckNotifications.first().resolvedAt) - assertEquals(null, stuckNotifications.last().resolvedAt) - } - - @Test - fun `stop completion resolves active stuck notification`() { - val teacher = userRepository.save(activeTeacher("owner-resolve-event@example.com")) - val pupil = userRepository.save(activePupil("pupil-resolve-event")) - val classroom = createClassroom("EVENTRESOLVE1", teacher) - val stop = createStop("event-resolve-stop", "Resolve stop", 1) - seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) - val pupilToken = pupilAccessToken("pupil-resolve-event", "secret123") - - repeat(5) { - wrongAttempt(classroom.id, requireNotNull(pupil.id), requireNotNull(stop.id), pupilToken) - } - - mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { - with(csrf()) - contentType = MediaType.APPLICATION_JSON - header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") - content = """{"status":"COMPLETED"}""" - }.andExpect { - status { isOk() } - } - - val stuckNotification = awaitNotifications( - predicate = { notifications -> notifications.size == 1 && notifications.single().resolvedAt != null }, - ) { - teacherNotificationRepository.findAll() - .filter { it.teacherUserId == teacher.id && it.type == NotificationType.PUPIL_STUCK } - }.single() - assertNotNull(stuckNotification.resolvedAt) - } - - private fun wrongAttempt(classroomId: Long, pupilUserId: Long, stopId: Long, token: String) { - mockMvc.post("/api/v1/classrooms/$classroomId/pupils/$pupilUserId/stop-progress/$stopId/attempt-outcomes") { - with(csrf()) - contentType = MediaType.APPLICATION_JSON - header(HttpHeaders.AUTHORIZATION, "Bearer $token") content = """{"correct":false}""" }.andExpect { - status { isOk() } + status { isNotFound() } } - } - private fun awaitNotifications( - timeoutMillis: Long = 1_500, - predicate: (List) -> Boolean = { it.isNotEmpty() }, - supplier: () -> List, - ): List { - val deadline = System.currentTimeMillis() + timeoutMillis - var notifications = supplier() - while (!predicate(notifications) && System.currentTimeMillis() < deadline) { - Thread.sleep(50) - notifications = supplier() - } - return notifications + assertEquals(0, teacherNotificationRepository.count()) } private fun createClassroom(code: String, owner: User): Classroom = @@ -310,17 +155,6 @@ class NotificationEventIntegrationTests { ) } - private fun teacherAccessToken(email: String, password: String): String = - jsonMapper.readTree( - mockMvc.post("/api/v1/auth/teacher/login") { - with(csrf()) - contentType = MediaType.APPLICATION_JSON - content = """{"email":"$email","password":"$password"}""" - }.andExpect { - status { isOk() } - }.andReturn().response.contentAsString, - ).get("accessToken").asText() - private fun pupilAccessToken(username: String, password: String): String = jsonMapper.readTree( mockMvc.post("/api/v1/auth/pupil/login") { diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt index d07104e7..49a538a8 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt @@ -107,6 +107,7 @@ class NotificationPersistenceTests @Autowired constructor( sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, sourceKey = "stop-progress:1:2:3", threadKey = "stuck:1:2:3", + activeThreadKey = "stuck:1:2:3", title = "Elev star fast", message = "En elev trenger hjelp.", payloadJson = """{"stopId":3}""", @@ -115,9 +116,48 @@ class NotificationPersistenceTests @Autowired constructor( assertNotNull(saved.id) assertEquals("stuck:1:2:3", saved.threadKey) + assertEquals("stuck:1:2:3", saved.activeThreadKey) assertEquals("""{"stopId":3}""", saved.payloadJson) } + @Test + fun `enforces one active thread per teacher`() { + val teacher = teacher() + val classroom = classroom(teacher) + + teacherNotificationRepository.saveAndFlush( + TeacherNotification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + pupilUserId = null, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "stuck-1", + threadKey = "stuck:1:2:3", + activeThreadKey = "stuck:1:2:3", + title = "Elev star fast", + message = "En elev trenger hjelp.", + ), + ) + + assertThrows { + teacherNotificationRepository.saveAndFlush( + TeacherNotification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + pupilUserId = null, + type = NotificationType.PUPIL_STUCK, + sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, + sourceKey = "stuck-2", + threadKey = "stuck:1:2:3", + activeThreadKey = "stuck:1:2:3", + title = "Elev star fast", + message = "En elev trenger hjelp.", + ), + ) + } + } + @Test fun `enforces one mute per teacher classroom and type`() { val teacher = teacher() @@ -161,6 +201,7 @@ class NotificationPersistenceTests @Autowired constructor( }, sourceKey = "${type.name.lowercase()}-${sequence.incrementAndGet()}", threadKey = null, + activeThreadKey = null, title = type.name, message = "Notification for $type", readAt = readAt, From c75d38b51c341d0486b601c59e412dd815ecc089 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 09:51:46 +0200 Subject: [PATCH 06/15] Remove now stale sourceKind and sourceKey --- docs/notifications-architecture.md | 10 ++++------ .../application/NotificationDeliveryService.kt | 2 -- .../notification/application/NotificationDraft.kt | 3 --- .../application/TeacherNotificationEventListener.kt | 7 ------- .../notification/domain/NotificationSourceKind.kt | 10 ---------- .../notification/domain/TeacherNotification.kt | 5 ----- .../V16__create_teacher_notifications_table.sql | 2 -- .../NotificationControllerIntegrationTests.kt | 8 +------- .../NotificationDeliveryServiceTests.kt | 9 --------- .../notification/NotificationInboxServiceTests.kt | 4 +--- .../notification/NotificationPersistenceTests.kt | 13 ------------- 11 files changed, 6 insertions(+), 67 deletions(-) delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt diff --git a/docs/notifications-architecture.md b/docs/notifications-architecture.md index 51c2d5cb..c1f1ad43 100644 --- a/docs/notifications-architecture.md +++ b/docs/notifications-architecture.md @@ -47,8 +47,6 @@ Important fields: - `classroom_id` - `pupil_user_id` - `type` -- `source_kind` -- `source_key` - `thread_key` - `active_thread_key` - `title` @@ -126,10 +124,10 @@ These endpoints operate on the authenticated teacher's personal inbox rows only. 1. Add a typed business event in `shared/events`. 2. Publish it from the source service through `DomainEventPublisher`. 3. Add a listener method in `TeacherNotificationEventListener`. -4. Build a `NotificationDraft` there, including a stable `sourceKey` and, if - needed, a `threadKey`. -5. Reuse `NotificationSourceKind` and `NotificationType` if possible. Add new - enum values only when the business concept is genuinely new. +4. Build a `NotificationDraft` there and include a stable `threadKey` when the + notification represents an active state that may be reopened or resolved. +5. Reuse `NotificationType` if possible. Add a new enum value only when the + business concept is genuinely new. 6. Add or update integration tests proving one notification per unmuted teacher recipient and correct deduplication behavior. diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt index 96d999e1..bd090a4a 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt @@ -37,8 +37,6 @@ class NotificationDeliveryService( classroomId = draft.classroomId, pupilUserId = draft.pupilUserId, type = draft.type, - sourceKind = draft.sourceKind, - sourceKey = draft.sourceKey, threadKey = draft.threadKey, activeThreadKey = draft.threadKey, title = draft.title, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt index b9ab72ec..7c579500 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt @@ -1,6 +1,5 @@ package edu.ntnu.idi.idatt.backend.notification.application -import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType /** @@ -10,8 +9,6 @@ data class NotificationDraft( val classroomId: Long, val pupilUserId: Long?, val type: NotificationType, - val sourceKind: NotificationSourceKind, - val sourceKey: String, val threadKey: String?, val title: String, val message: String, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt index b8f22365..2197211a 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt @@ -1,6 +1,5 @@ package edu.ntnu.idi.idatt.backend.notification.application -import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent @@ -31,8 +30,6 @@ class TeacherNotificationEventListener( classroomId = event.classroomId, pupilUserId = event.pupilUserId, type = NotificationType.MAP_STOP_COMPLETED, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = threadKey, threadKey = threadKey, title = "Omrade fullfort", message = "${context.pupilDisplayName} har fullfort omradet ${context.stopTitle} i ${context.classroomTitle}.", @@ -59,8 +56,6 @@ class TeacherNotificationEventListener( classroomId = event.classroomId, pupilUserId = event.pupilUserId, type = NotificationType.GAME_COMPLETED, - sourceKind = NotificationSourceKind.GAME_PROGRESS, - sourceKey = threadKey, threadKey = threadKey, title = "Spillet fullfort", message = "${context.pupilDisplayName} har fullfort spillet i ${context.classroomTitle}.", @@ -87,8 +82,6 @@ class TeacherNotificationEventListener( classroomId = event.classroomId, pupilUserId = event.pupilUserId, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = threadKey, threadKey = threadKey, title = "Elev star fast", message = "${context.pupilDisplayName} star fast ved ${context.stopTitle} i ${context.classroomTitle}.", diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt deleted file mode 100644 index 8f3cbaca..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationSourceKind.kt +++ /dev/null @@ -1,10 +0,0 @@ -package edu.ntnu.idi.idatt.backend.notification.domain - -/** - * Identifies the business source that produced a teacher notification. - */ -enum class NotificationSourceKind { - MAP_STOP_PROGRESS, - GAME_PROGRESS, - WEEKLY_MYSTERY_SUBMISSION, -} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt index 1ec90ed6..b4f34367 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt @@ -30,11 +30,6 @@ class TeacherNotification( @Enumerated(EnumType.STRING) @Column(nullable = false) var type: NotificationType, - @Enumerated(EnumType.STRING) - @Column(name = "source_kind", nullable = false) - var sourceKind: NotificationSourceKind, - @Column(name = "source_key", nullable = false, length = 255) - var sourceKey: String, @Column(name = "thread_key", length = 255) var threadKey: String? = null, @Column(name = "active_thread_key", length = 255) diff --git a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql index 185a3b69..55562078 100644 --- a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql +++ b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql @@ -4,8 +4,6 @@ CREATE TABLE teacher_notifications ( classroom_id BIGINT NOT NULL, pupil_user_id BIGINT, type ENUM('MAP_STOP_COMPLETED', 'GAME_COMPLETED', 'PUPIL_STUCK', 'WEEKLY_MYSTERY_SUBMITTED') NOT NULL, - source_kind ENUM('MAP_STOP_PROGRESS', 'GAME_PROGRESS', 'WEEKLY_MYSTERY_SUBMISSION') NOT NULL, - source_key VARCHAR(255) NOT NULL, thread_key VARCHAR(255), active_thread_key VARCHAR(255), title VARCHAR(255) NOT NULL, diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt index 51e3348d..35d11dc1 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt @@ -9,7 +9,6 @@ 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.notification.domain.NotificationSourceKind import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository @@ -270,13 +269,8 @@ class NotificationControllerIntegrationTests { classroomId = classroomId, pupilUserId = null, type = type, - sourceKind = when (type) { - NotificationType.MAP_STOP_COMPLETED, NotificationType.PUPIL_STUCK -> NotificationSourceKind.MAP_STOP_PROGRESS - NotificationType.GAME_COMPLETED -> NotificationSourceKind.GAME_PROGRESS - NotificationType.WEEKLY_MYSTERY_SUBMITTED -> NotificationSourceKind.WEEKLY_MYSTERY_SUBMISSION - }, - sourceKey = "${type.name.lowercase()}-${System.nanoTime()}", threadKey = if (type == NotificationType.PUPIL_STUCK) "stuck:$classroomId:$teacherUserId" else null, + activeThreadKey = if (type == NotificationType.PUPIL_STUCK) "stuck:$classroomId:$teacherUserId" else null, title = "Notification $type", message = "Notification for $type", readAt = readAt, diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt index b1cd9c2c..55b3abe8 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt @@ -3,7 +3,6 @@ package edu.ntnu.idi.idatt.backend.notification import edu.ntnu.idi.idatt.backend.notification.application.ClassroomNotificationRecipientResolver import edu.ntnu.idi.idatt.backend.notification.application.NotificationDeliveryService import edu.ntnu.idi.idatt.backend.notification.application.NotificationDraft -import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository @@ -44,8 +43,6 @@ class NotificationDeliveryServiceTests { classroomId = 42L, pupilUserId = 7L, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "stuck-42-7-3", threadKey = "stuck:42:7:3", title = "Elev star fast", message = "En elev trenger hjelp.", @@ -88,8 +85,6 @@ class NotificationDeliveryServiceTests { classroomId = 42L, pupilUserId = 7L, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "existing", threadKey = "stuck:42:7:3", activeThreadKey = "stuck:42:7:3", title = "Existing", @@ -113,8 +108,6 @@ class NotificationDeliveryServiceTests { classroomId = 42L, pupilUserId = 7L, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "stuck-1", threadKey = "stuck:42:7:3", activeThreadKey = "stuck:42:7:3", title = "Elev star fast", @@ -126,8 +119,6 @@ class NotificationDeliveryServiceTests { classroomId = 42L, pupilUserId = 7L, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "stuck-2", threadKey = "stuck:42:7:3", activeThreadKey = "stuck:42:7:3", title = "Elev star fast", diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt index dfa9de63..256eea04 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt @@ -5,7 +5,6 @@ import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import edu.ntnu.idi.idatt.backend.notification.application.NotificationInboxService -import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository @@ -98,9 +97,8 @@ class NotificationInboxServiceTests { classroomId = 42L, pupilUserId = 7L, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "stuck-1", threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", title = "Elev star fast", message = "En elev trenger hjelp.", ) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt index 49a538a8..8d05cf50 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt @@ -7,7 +7,6 @@ import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository -import edu.ntnu.idi.idatt.backend.notification.domain.NotificationSourceKind import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute @@ -104,8 +103,6 @@ class NotificationPersistenceTests @Autowired constructor( classroomId = classroom.id, pupilUserId = null, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "stop-progress:1:2:3", threadKey = "stuck:1:2:3", activeThreadKey = "stuck:1:2:3", title = "Elev star fast", @@ -131,8 +128,6 @@ class NotificationPersistenceTests @Autowired constructor( classroomId = classroom.id, pupilUserId = null, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "stuck-1", threadKey = "stuck:1:2:3", activeThreadKey = "stuck:1:2:3", title = "Elev star fast", @@ -147,8 +142,6 @@ class NotificationPersistenceTests @Autowired constructor( classroomId = classroom.id, pupilUserId = null, type = NotificationType.PUPIL_STUCK, - sourceKind = NotificationSourceKind.MAP_STOP_PROGRESS, - sourceKey = "stuck-2", threadKey = "stuck:1:2:3", activeThreadKey = "stuck:1:2:3", title = "Elev star fast", @@ -194,12 +187,6 @@ class NotificationPersistenceTests @Autowired constructor( classroomId = classroomId, pupilUserId = null, type = type, - sourceKind = when (type) { - NotificationType.MAP_STOP_COMPLETED, NotificationType.PUPIL_STUCK -> NotificationSourceKind.MAP_STOP_PROGRESS - NotificationType.GAME_COMPLETED -> NotificationSourceKind.GAME_PROGRESS - NotificationType.WEEKLY_MYSTERY_SUBMITTED -> NotificationSourceKind.WEEKLY_MYSTERY_SUBMISSION - }, - sourceKey = "${type.name.lowercase()}-${sequence.incrementAndGet()}", threadKey = null, activeThreadKey = null, title = type.name, From 22467425cc561da690974a61ec699743c5423e5d Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 09:52:54 +0200 Subject: [PATCH 07/15] Small fixes --- .../notification/NotificationControllerIntegrationTests.kt | 2 +- .../backend/notification/NotificationDeliveryServiceTests.kt | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt index 35d11dc1..d2f7db50 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt @@ -245,7 +245,7 @@ class NotificationControllerIntegrationTests { @Test fun `teacher cannot mute classroom they do not administer`() { val owner = userRepository.save(activeTeacher("owner-no-mute@example.com")) - val outsider = userRepository.save(activeTeacher("outsider-no-mute@example.com")) + userRepository.save(activeTeacher("outsider-no-mute@example.com")) val classroom = createClassroom("MUTE2", owner) val accessToken = teacherAccessToken("outsider-no-mute@example.com", "secret123") diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt index 55b3abe8..b906ee2c 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt @@ -17,7 +17,6 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.Mockito.`when` -import java.time.Instant class NotificationDeliveryServiceTests { private lateinit var teacherNotificationRepository: TeacherNotificationRepository From c7ec1c1e4e3cee3f0d3160fd50f5ed9467212363 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 10:00:02 +0200 Subject: [PATCH 08/15] Notifications returns a render code to support languages in frontend --- docs/notifications-architecture.md | 10 +++--- .../api/NotificationApiMappings.kt | 4 +-- .../notification/api/NotificationResponse.kt | 4 +-- .../NotificationDeliveryService.kt | 4 +-- .../application/NotificationDraft.kt | 7 ++-- .../NotificationEventContextResolver.kt | 4 +-- .../TeacherNotificationEventListener.kt | 32 +++++++++++++------ .../domain/NotificationRenderCode.kt | 13 ++++++++ .../domain/TeacherNotification.kt | 8 ++--- ...16__create_teacher_notifications_table.sql | 4 +-- .../NotificationControllerIntegrationTests.kt | 14 ++++++-- .../NotificationDeliveryServiceTests.kt | 17 +++++----- .../NotificationInboxServiceTests.kt | 5 +-- .../NotificationPersistenceTests.kt | 27 +++++++++++----- 14 files changed, 102 insertions(+), 51 deletions(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationRenderCode.kt diff --git a/docs/notifications-architecture.md b/docs/notifications-architecture.md index c1f1ad43..f1e1afc5 100644 --- a/docs/notifications-architecture.md +++ b/docs/notifications-architecture.md @@ -49,8 +49,8 @@ Important fields: - `type` - `thread_key` - `active_thread_key` -- `title` -- `message` +- `render_code` +- `render_args_json` - `payload_json` - `read_at` - `dismissed_at` @@ -126,9 +126,11 @@ These endpoints operate on the authenticated teacher's personal inbox rows only. 3. Add a listener method in `TeacherNotificationEventListener`. 4. Build a `NotificationDraft` there and include a stable `threadKey` when the notification represents an active state that may be reopened or resolved. -5. Reuse `NotificationType` if possible. Add a new enum value only when the +5. Set a stable frontend `renderCode` and include all localized template inputs + in `renderArgsJson` instead of storing backend-authored display strings. +6. Reuse `NotificationType` if possible. Add a new enum value only when the business concept is genuinely new. -6. Add or update integration tests proving one notification per unmuted teacher +7. Add or update integration tests proving one notification per unmuted teacher recipient and correct deduplication behavior. Do not call notification repositories from source services. diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt index b4e94334..3af7c392 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt @@ -11,8 +11,8 @@ fun TeacherNotification.toResponse(): NotificationResponse = classroomId = classroomId, pupilUserId = pupilUserId, type = type, - title = title, - message = message, + renderCode = renderCode, + renderArgsJson = renderArgsJson, payloadJson = payloadJson, readAt = readAt, dismissedAt = dismissedAt, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt index f2f238a6..3f198b0a 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt @@ -8,8 +8,8 @@ data class NotificationResponse( val classroomId: Long, val pupilUserId: Long?, val type: NotificationType, - val title: String, - val message: String, + val renderCode: String, + val renderArgsJson: String?, val payloadJson: String?, val readAt: Instant?, val dismissedAt: Instant?, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt index bd090a4a..eb987a77 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt @@ -39,8 +39,8 @@ class NotificationDeliveryService( type = draft.type, threadKey = draft.threadKey, activeThreadKey = draft.threadKey, - title = draft.title, - message = draft.message, + renderCode = draft.renderCode.code, + renderArgsJson = draft.renderArgsJson, payloadJson = draft.payloadJson, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt index 7c579500..e443ad2f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt @@ -1,16 +1,17 @@ package edu.ntnu.idi.idatt.backend.notification.application +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationRenderCode import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType /** - * Fully formatted teacher notification ready for fan-out. + * Notification ready for fan-out with frontend render metadata. */ data class NotificationDraft( val classroomId: Long, val pupilUserId: Long?, val type: NotificationType, val threadKey: String?, - val title: String, - val message: String, + val renderCode: NotificationRenderCode, + val renderArgsJson: String?, val payloadJson: String?, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt index af0c80fb..792b8dbc 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt @@ -16,7 +16,7 @@ data class StopNotificationContext( ) /** - * Resolves user-facing names needed to format teacher notifications. + * Resolves domain context needed to build teacher notification render arguments. */ @Component class NotificationEventContextResolver( @@ -53,6 +53,6 @@ class NotificationEventContextResolver( ) } - fun payloadJson(vararg entries: Pair): String = + fun json(vararg entries: Pair): String = objectMapper.writeValueAsString(linkedMapOf(*entries)) } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt index 2197211a..960661eb 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt @@ -1,5 +1,6 @@ package edu.ntnu.idi.idatt.backend.notification.application +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationRenderCode import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent @@ -31,9 +32,13 @@ class TeacherNotificationEventListener( pupilUserId = event.pupilUserId, type = NotificationType.MAP_STOP_COMPLETED, threadKey = threadKey, - title = "Omrade fullfort", - message = "${context.pupilDisplayName} har fullfort omradet ${context.stopTitle} i ${context.classroomTitle}.", - payloadJson = notificationEventContextResolver.payloadJson( + renderCode = NotificationRenderCode.MAP_STOP_COMPLETED, + renderArgsJson = notificationEventContextResolver.json( + "classroomTitle" to context.classroomTitle, + "pupilDisplayName" to context.pupilDisplayName, + "stopTitle" to context.stopTitle, + ), + payloadJson = notificationEventContextResolver.json( "classroomId" to event.classroomId, "pupilUserId" to event.pupilUserId, "stopId" to event.stopId, @@ -57,9 +62,12 @@ class TeacherNotificationEventListener( pupilUserId = event.pupilUserId, type = NotificationType.GAME_COMPLETED, threadKey = threadKey, - title = "Spillet fullfort", - message = "${context.pupilDisplayName} har fullfort spillet i ${context.classroomTitle}.", - payloadJson = notificationEventContextResolver.payloadJson( + renderCode = NotificationRenderCode.GAME_COMPLETED, + renderArgsJson = notificationEventContextResolver.json( + "classroomTitle" to context.classroomTitle, + "pupilDisplayName" to context.pupilDisplayName, + ), + payloadJson = notificationEventContextResolver.json( "classroomId" to event.classroomId, "pupilUserId" to event.pupilUserId, "stopId" to event.stopId, @@ -83,13 +91,17 @@ class TeacherNotificationEventListener( pupilUserId = event.pupilUserId, type = NotificationType.PUPIL_STUCK, threadKey = threadKey, - title = "Elev star fast", - message = "${context.pupilDisplayName} star fast ved ${context.stopTitle} i ${context.classroomTitle}.", - payloadJson = notificationEventContextResolver.payloadJson( + renderCode = NotificationRenderCode.PUPIL_STUCK, + renderArgsJson = notificationEventContextResolver.json( + "classroomTitle" to context.classroomTitle, + "pupilDisplayName" to context.pupilDisplayName, + "stopTitle" to context.stopTitle, + "consecutiveWrongAttempts" to event.consecutiveWrongAttempts, + ), + payloadJson = notificationEventContextResolver.json( "classroomId" to event.classroomId, "pupilUserId" to event.pupilUserId, "stopId" to event.stopId, - "consecutiveWrongAttempts" to event.consecutiveWrongAttempts, ), ), ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationRenderCode.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationRenderCode.kt new file mode 100644 index 00000000..6ad487fb --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/NotificationRenderCode.kt @@ -0,0 +1,13 @@ +package edu.ntnu.idi.idatt.backend.notification.domain + +/** + * Stable frontend rendering keys for teacher notifications. + */ +enum class NotificationRenderCode( + val code: String, +) { + MAP_STOP_COMPLETED("notifications.map-stop-completed"), + GAME_COMPLETED("notifications.game-completed"), + PUPIL_STUCK("notifications.pupil-stuck"), + WEEKLY_MYSTERY_SUBMITTED("notifications.weekly-mystery-submitted"), +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt index b4f34367..24bbb0cc 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt @@ -34,10 +34,10 @@ class TeacherNotification( var threadKey: String? = null, @Column(name = "active_thread_key", length = 255) var activeThreadKey: String? = null, - @Column(nullable = false, length = 255) - var title: String, - @Column(nullable = false, columnDefinition = "TEXT") - var message: String, + @Column(name = "render_code", nullable = false, length = 255) + var renderCode: String, + @Column(name = "render_args_json", columnDefinition = "TEXT") + var renderArgsJson: String? = null, @Column(name = "payload_json", columnDefinition = "TEXT") var payloadJson: String? = null, @Column(name = "read_at") diff --git a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql index 55562078..87aac659 100644 --- a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql +++ b/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql @@ -6,8 +6,8 @@ CREATE TABLE teacher_notifications ( type ENUM('MAP_STOP_COMPLETED', 'GAME_COMPLETED', 'PUPIL_STUCK', 'WEEKLY_MYSTERY_SUBMITTED') NOT NULL, thread_key VARCHAR(255), active_thread_key VARCHAR(255), - title VARCHAR(255) NOT NULL, - message TEXT NOT NULL, + render_code VARCHAR(255) NOT NULL, + render_args_json TEXT, payload_json TEXT, read_at DATETIME(6), dismissed_at DATETIME(6), diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt index d2f7db50..c24a7af9 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt @@ -9,6 +9,7 @@ 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.notification.domain.NotificationRenderCode import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository @@ -119,6 +120,7 @@ class NotificationControllerIntegrationTests { status { isOk() } jsonPath("$.items.length()") { value(1) } jsonPath("$.items[0].type") { value(NotificationType.MAP_STOP_COMPLETED.name) } + jsonPath("$.items[0].renderCode") { value(NotificationRenderCode.MAP_STOP_COMPLETED.code) } jsonPath("$.totalElements") { value(1) } } @@ -271,12 +273,20 @@ class NotificationControllerIntegrationTests { type = type, threadKey = if (type == NotificationType.PUPIL_STUCK) "stuck:$classroomId:$teacherUserId" else null, activeThreadKey = if (type == NotificationType.PUPIL_STUCK) "stuck:$classroomId:$teacherUserId" else null, - title = "Notification $type", - message = "Notification for $type", + renderCode = renderCodeFor(type), + renderArgsJson = """{"type":"$type"}""", readAt = readAt, dismissedAt = dismissedAt, ) + private fun renderCodeFor(type: NotificationType): String = + when (type) { + NotificationType.MAP_STOP_COMPLETED -> NotificationRenderCode.MAP_STOP_COMPLETED.code + NotificationType.GAME_COMPLETED -> NotificationRenderCode.GAME_COMPLETED.code + NotificationType.PUPIL_STUCK -> NotificationRenderCode.PUPIL_STUCK.code + NotificationType.WEEKLY_MYSTERY_SUBMITTED -> NotificationRenderCode.WEEKLY_MYSTERY_SUBMITTED.code + } + private fun createClassroom(code: String, owner: User): Classroom = classroomRepository.saveAndFlush( Classroom( diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt index b906ee2c..e87356f7 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt @@ -3,6 +3,7 @@ package edu.ntnu.idi.idatt.backend.notification import edu.ntnu.idi.idatt.backend.notification.application.ClassroomNotificationRecipientResolver import edu.ntnu.idi.idatt.backend.notification.application.NotificationDeliveryService import edu.ntnu.idi.idatt.backend.notification.application.NotificationDraft +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationRenderCode import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository @@ -43,8 +44,8 @@ class NotificationDeliveryServiceTests { pupilUserId = 7L, type = NotificationType.PUPIL_STUCK, threadKey = "stuck:42:7:3", - title = "Elev star fast", - message = "En elev trenger hjelp.", + renderCode = NotificationRenderCode.PUPIL_STUCK, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", payloadJson = """{"stopId":3}""", ) @@ -86,8 +87,8 @@ class NotificationDeliveryServiceTests { type = NotificationType.PUPIL_STUCK, threadKey = "stuck:42:7:3", activeThreadKey = "stuck:42:7:3", - title = "Existing", - message = "Existing", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", ), ), ) @@ -109,8 +110,8 @@ class NotificationDeliveryServiceTests { type = NotificationType.PUPIL_STUCK, threadKey = "stuck:42:7:3", activeThreadKey = "stuck:42:7:3", - title = "Elev star fast", - message = "En elev trenger hjelp.", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", ) val unresolvedSecond = TeacherNotification( id = 2L, @@ -120,8 +121,8 @@ class NotificationDeliveryServiceTests { type = NotificationType.PUPIL_STUCK, threadKey = "stuck:42:7:3", activeThreadKey = "stuck:42:7:3", - title = "Elev star fast", - message = "En elev trenger hjelp.", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", ) `when`( teacherNotificationRepository.findAllByClassroomIdAndThreadKeyAndResolvedAtIsNull( diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt index 256eea04..767a00f7 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt @@ -5,6 +5,7 @@ import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import edu.ntnu.idi.idatt.backend.notification.application.NotificationInboxService +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationRenderCode import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository @@ -99,7 +100,7 @@ class NotificationInboxServiceTests { type = NotificationType.PUPIL_STUCK, threadKey = "stuck:42:7:3", activeThreadKey = "stuck:42:7:3", - title = "Elev star fast", - message = "En elev trenger hjelp.", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", ) } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt index 8d05cf50..74f5bc80 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt @@ -7,6 +7,7 @@ import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationRenderCode import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute @@ -105,8 +106,8 @@ class NotificationPersistenceTests @Autowired constructor( type = NotificationType.PUPIL_STUCK, threadKey = "stuck:1:2:3", activeThreadKey = "stuck:1:2:3", - title = "Elev star fast", - message = "En elev trenger hjelp.", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", payloadJson = """{"stopId":3}""", ), ) @@ -114,6 +115,8 @@ class NotificationPersistenceTests @Autowired constructor( assertNotNull(saved.id) assertEquals("stuck:1:2:3", saved.threadKey) assertEquals("stuck:1:2:3", saved.activeThreadKey) + assertEquals(NotificationRenderCode.PUPIL_STUCK.code, saved.renderCode) + assertEquals("""{"stopTitle":"Omrade 3"}""", saved.renderArgsJson) assertEquals("""{"stopId":3}""", saved.payloadJson) } @@ -130,8 +133,8 @@ class NotificationPersistenceTests @Autowired constructor( type = NotificationType.PUPIL_STUCK, threadKey = "stuck:1:2:3", activeThreadKey = "stuck:1:2:3", - title = "Elev star fast", - message = "En elev trenger hjelp.", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", ), ) @@ -144,8 +147,8 @@ class NotificationPersistenceTests @Autowired constructor( type = NotificationType.PUPIL_STUCK, threadKey = "stuck:1:2:3", activeThreadKey = "stuck:1:2:3", - title = "Elev star fast", - message = "En elev trenger hjelp.", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", ), ) } @@ -189,12 +192,20 @@ class NotificationPersistenceTests @Autowired constructor( type = type, threadKey = null, activeThreadKey = null, - title = type.name, - message = "Notification for $type", + renderCode = renderCodeFor(type), + renderArgsJson = """{"type":"$type"}""", readAt = readAt, dismissedAt = dismissedAt, ) + private fun renderCodeFor(type: NotificationType): String = + when (type) { + NotificationType.MAP_STOP_COMPLETED -> NotificationRenderCode.MAP_STOP_COMPLETED.code + NotificationType.GAME_COMPLETED -> NotificationRenderCode.GAME_COMPLETED.code + NotificationType.PUPIL_STUCK -> NotificationRenderCode.PUPIL_STUCK.code + NotificationType.WEEKLY_MYSTERY_SUBMITTED -> NotificationRenderCode.WEEKLY_MYSTERY_SUBMITTED.code + } + private fun teacher(): User = sequence.incrementAndGet().let { suffix -> userRepository.saveAndFlush( From febf57b5279e7ca0f373f40997c68437b6206617 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 10:26:44 +0200 Subject: [PATCH 09/15] Make PupilStopProgressService use notification events --- .../application/PupilStopProgressService.kt | 99 +++++++ .../NotificationDeliveryService.kt | 5 +- .../TeacherNotificationEventListener.kt | 11 +- .../mapstops/PupilStopProgressServiceTests.kt | 257 ++++++++++++++++-- .../NotificationEventIntegrationTests.kt | 34 ++- 5 files changed, 379 insertions(+), 27 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 59d1a99a..cdc4c91f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/game/mapstops/application/PupilStopProgressService.kt @@ -5,6 +5,11 @@ import edu.ntnu.idi.idatt.backend.game.mapstops.domain.PupilStopProgress import edu.ntnu.idi.idatt.backend.game.mapstops.domain.StopProgressStatus import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgressRepository +import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher +import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -20,6 +25,7 @@ import java.time.Instant class PupilStopProgressService( private val progressRepository: PupilStopProgressRepository, private val mapStopRepository: MapStopsRepository, + private val domainEventPublisher: DomainEventPublisher, ) { /** * Returns all stop progress records for a pupil in a classroom. @@ -87,8 +93,10 @@ class PupilStopProgressService( progress.status = next if (next == StopProgressStatus.COMPLETED && progress.completedAt == null) { + resolveStuckIfNeeded(pupilUserId, classroomId, stopId, progress) progress.completedAt = Instant.now() unlockNextStop(pupilUserId, classroomId, stopId, activeStops) + publishCompletionEvents(pupilUserId, classroomId, stopId, progress) } } command.currentTaskId?.let { progress.currentTaskId = it } @@ -98,6 +106,49 @@ class PupilStopProgressService( return progressRepository.save(progress) } + @Transactional + fun recordVerifiedAttemptOutcome( + pupilUserId: Long, + classroomId: Long, + stopId: Long, + correct: Boolean, + ): PupilStopProgress { + val progress = getProgressForStop(pupilUserId, classroomId, stopId) + + if (progress.status == StopProgressStatus.COMPLETED) { + return progress + } + + val wasStuck = progress.consecutiveWrongAttempts >= STUCK_THRESHOLD + + if (correct) { + progress.consecutiveWrongAttempts = 0 + if (wasStuck) { + domainEventPublisher.publish( + PupilRecoveredFromStuckEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + ) + } + } else { + progress.consecutiveWrongAttempts += 1 + if (!wasStuck && progress.consecutiveWrongAttempts >= STUCK_THRESHOLD) { + domainEventPublisher.publish( + PupilStuckThresholdReachedEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + consecutiveWrongAttempts = progress.consecutiveWrongAttempts, + ), + ) + } + } + + return progressRepository.save(progress) + } + /** * Verifies that the stop preceding [stopId] in the active stop order is completed * for the given pupil in the given classroom, preventing pupils from skipping stops. @@ -183,4 +234,52 @@ class PupilStopProgressService( ) } } + + private fun resolveStuckIfNeeded( + pupilUserId: Long, + classroomId: Long, + stopId: Long, + progress: PupilStopProgress, + ) { + val wasStuck = progress.consecutiveWrongAttempts >= STUCK_THRESHOLD + progress.consecutiveWrongAttempts = 0 + if (wasStuck) { + domainEventPublisher.publish( + PupilRecoveredFromStuckEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + ) + } + } + + private fun publishCompletionEvents( + pupilUserId: Long, + classroomId: Long, + stopId: Long, + progress: PupilStopProgress, + ) { + domainEventPublisher.publish( + MapStopCompletedEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + ) + + if (progress.stop.isActive == true && progress.stop.isFinalBoss == true) { + domainEventPublisher.publish( + PupilGameCompletedEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + ) + } + } + + companion object { + private const val STUCK_THRESHOLD = 5 + } } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt index eb987a77..9d84c0bb 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt @@ -5,6 +5,7 @@ import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificatio import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import java.time.Instant @@ -17,7 +18,7 @@ class NotificationDeliveryService( private val teacherNotificationMuteRepository: TeacherNotificationMuteRepository, private val recipientResolver: ClassroomNotificationRecipientResolver, ) { - @Transactional + @Transactional(propagation = Propagation.REQUIRES_NEW) fun deliverToClassroomTeachers(draft: NotificationDraft): List { val recipients = recipientResolver.resolveTeacherRecipientIds(draft.classroomId) val notifications = mutableListOf() @@ -60,7 +61,7 @@ class NotificationDeliveryService( return notifications } - @Transactional + @Transactional(propagation = Propagation.REQUIRES_NEW) fun resolveThread(classroomId: Long, threadKey: String): Int { val now = Instant.now() val activeNotifications = teacherNotificationRepository.findAllByClassroomIdAndThreadKeyAndResolvedAtIsNull( diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt index 960661eb..7271f3dd 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt @@ -6,8 +6,9 @@ import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent -import org.springframework.context.event.EventListener import org.springframework.stereotype.Component +import org.springframework.transaction.event.TransactionPhase +import org.springframework.transaction.event.TransactionalEventListener /** * Translates business events into teacher inbox notifications. @@ -17,7 +18,7 @@ class TeacherNotificationEventListener( private val notificationDeliveryService: NotificationDeliveryService, private val notificationEventContextResolver: NotificationEventContextResolver, ) { - @EventListener + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onMapStopCompleted(event: MapStopCompletedEvent) { val context = notificationEventContextResolver.resolveStopContext( classroomId = event.classroomId, @@ -47,7 +48,7 @@ class TeacherNotificationEventListener( ) } - @EventListener + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onGameCompleted(event: PupilGameCompletedEvent) { val context = notificationEventContextResolver.resolveStopContext( classroomId = event.classroomId, @@ -76,7 +77,7 @@ class TeacherNotificationEventListener( ) } - @EventListener + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onPupilStuck(event: PupilStuckThresholdReachedEvent) { val context = notificationEventContextResolver.resolveStopContext( classroomId = event.classroomId, @@ -107,7 +108,7 @@ class TeacherNotificationEventListener( ) } - @EventListener + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onPupilRecovered(event: PupilRecoveredFromStuckEvent) { notificationDeliveryService.resolveThread( classroomId = event.classroomId, 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 8859649f..f3a692e1 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 @@ -12,9 +12,16 @@ import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgress import edu.ntnu.idi.idatt.backend.iam.domain.User import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus +import edu.ntnu.idi.idatt.backend.shared.events.DomainEvent +import edu.ntnu.idi.idatt.backend.shared.events.DomainEventPublisher +import edu.ntnu.idi.idatt.backend.shared.events.MapStopCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilGameCompletedEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.ArgumentMatchers.any @@ -28,7 +35,7 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns all progress records for given pupil and classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val records = listOf(progress(stopId = 1L), progress(stopId = 2L)) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(records) @@ -42,7 +49,7 @@ class PupilStopProgressServiceTests { fun `get progress for pupil returns empty list when pupil has no records in classroom`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) Mockito.`when`(progressRepository.findAllByIdPupilUserIdAndIdClassroomId(1L, 2L)).thenReturn(emptyList()) val result = service.getProgressForPupil(pupilUserId = 1L, classroomId = 2L) @@ -54,7 +61,7 @@ class PupilStopProgressServiceTests { fun `get progress for stop returns record when it exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 3L) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 3L)) @@ -69,7 +76,7 @@ class PupilStopProgressServiceTests { fun `get progress for stop throws 404 when no record exists`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) Mockito.`when`(progressRepository.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(1L, 2L, 99L)) .thenReturn(null) @@ -85,7 +92,8 @@ class PupilStopProgressServiceTests { fun `update progress transitions from LOCKED to NOT_STARTED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.LOCKED) stubFindAndSave(progressRepository, record) @@ -96,13 +104,15 @@ class PupilStopProgressServiceTests { ) assertEquals(StopProgressStatus.NOT_STARTED, result.status) + Mockito.verifyNoInteractions(domainEventPublisher) } @Test fun `update progress transitions from NOT_STARTED to IN_PROGRESS`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFindAndSave(progressRepository, record) @@ -113,13 +123,15 @@ class PupilStopProgressServiceTests { ) assertEquals(StopProgressStatus.IN_PROGRESS, result.status) + Mockito.verifyNoInteractions(domainEventPublisher) } @Test - fun `update progress transitions from IN_PROGRESS to COMPLETED and sets completedAt`() { + fun `update progress transitions from IN_PROGRESS to COMPLETED and publishes stop completed event`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -131,13 +143,15 @@ class PupilStopProgressServiceTests { assertEquals(StopProgressStatus.COMPLETED, result.status) assertNotNull(result.completedAt) + val publishedEvents = publishedEvents(domainEventPublisher, 1) + assertEquals(MapStopCompletedEvent::class, publishedEvents.single()::class) } @Test fun `update progress does not overwrite completedAt when stop is already completed`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS) stubFindAndSave(progressRepository, record) @@ -158,7 +172,8 @@ class PupilStopProgressServiceTests { fun `update progress rejects invalid transition from COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.COMPLETED) stubFind(progressRepository, record) @@ -171,13 +186,15 @@ class PupilStopProgressServiceTests { } assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, exception.statusCode) + Mockito.verifyNoInteractions(domainEventPublisher) } @Test fun `update progress rejects skipping from NOT_STARTED directly to COMPLETED`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.NOT_STARTED) stubFind(progressRepository, record) @@ -190,13 +207,14 @@ class PupilStopProgressServiceTests { } assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, exception.statusCode) + Mockito.verifyNoInteractions(domainEventPublisher) } @Test fun `update progress persists higher best score`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, bestScore = 40) stubFindAndSave(progressRepository, record) @@ -213,7 +231,7 @@ class PupilStopProgressServiceTests { fun `update progress does not overwrite best score when new value is lower`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L, bestScore = 90) stubFindAndSave(progressRepository, record) @@ -230,7 +248,7 @@ class PupilStopProgressServiceTests { fun `update progress sets current task id`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -247,7 +265,7 @@ class PupilStopProgressServiceTests { fun `update progress awards medal when medal flag is set`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val service = service(progressRepository, mapStopRepository) val record = progress(stopId = 1L) stubFindAndSave(progressRepository, record) @@ -264,7 +282,8 @@ class PupilStopProgressServiceTests { fun `update progress with all null fields changes nothing`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, bestScore = 55) stubFindAndSave(progressRepository, record) @@ -277,13 +296,15 @@ class PupilStopProgressServiceTests { assertEquals(StopProgressStatus.IN_PROGRESS, result.status) assertEquals(55, result.bestScore) assertNull(result.completedAt) + Mockito.verifyNoInteractions(domainEventPublisher) } @Test - fun `update progress completes active final boss without special side effects`() { + fun `update progress completes active final boss and publishes game completed event`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 99L, status = StopProgressStatus.IN_PROGRESS, isFinalBoss = true, isActive = true) stubFindAndSave(progressRepository, record) @@ -297,12 +318,192 @@ class PupilStopProgressServiceTests { assertEquals(StopProgressStatus.COMPLETED, record.status) assertNotNull(record.completedAt) + val publishedEvents = publishedEvents(domainEventPublisher, 2) + assertEquals(listOf(MapStopCompletedEvent::class, PupilGameCompletedEvent::class), publishedEvents.map { it::class }) + } + + @Test + fun `update progress completion resets stuck counter and publishes recovery when needed`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, consecutiveWrongAttempts = 5) + + stubFindAndSave(progressRepository, record) + + val result = service.updateProgress( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + command = UpdateStopProgressCommand(status = StopProgressStatus.COMPLETED, null, null, null), + ) + + assertEquals(0, result.consecutiveWrongAttempts) + val publishedEvents = publishedEvents(domainEventPublisher, 2) + assertEquals(listOf(PupilRecoveredFromStuckEvent::class, MapStopCompletedEvent::class), publishedEvents.map { it::class }) + } + + @Test + fun `record verified attempt outcome publishes stuck event on fifth wrong answer only`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, consecutiveWrongAttempts = 4) + + stubFindAndSave(progressRepository, record) + + val result = service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = false, + ) + + assertEquals(5, result.consecutiveWrongAttempts) + val publishedEvents = publishedEvents(domainEventPublisher, 1) + assertEquals(PupilStuckThresholdReachedEvent::class, publishedEvents.single()::class) + } + + @Test + fun `record verified attempt outcome does not republish stuck event after threshold`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, consecutiveWrongAttempts = 5) + + stubFindAndSave(progressRepository, record) + + val result = service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = false, + ) + + assertEquals(6, result.consecutiveWrongAttempts) + Mockito.verifyNoInteractions(domainEventPublisher) + } + + @Test + fun `record verified attempt outcome resets counter and publishes recovery on correct answer after stuck`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, consecutiveWrongAttempts = 5) + + stubFindAndSave(progressRepository, record) + + val result = service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = true, + ) + + assertEquals(0, result.consecutiveWrongAttempts) + val publishedEvents = publishedEvents(domainEventPublisher, 1) + assertEquals(PupilRecoveredFromStuckEvent::class, publishedEvents.single()::class) + } + + @Test + fun `record verified attempt outcome resets counter without publishing before stuck threshold`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, consecutiveWrongAttempts = 3) + + stubFindAndSave(progressRepository, record) + + val result = service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = true, + ) + + assertEquals(0, result.consecutiveWrongAttempts) + Mockito.verifyNoInteractions(domainEventPublisher) + } + + @Test + fun `record verified attempt outcome can publish stuck again after a recovery reset`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) + val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS, consecutiveWrongAttempts = 0) + + stubFindAndSave(progressRepository, record) + + repeat(5) { index -> + service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = false, + ) + if (index == 4) { + assertEquals(5, record.consecutiveWrongAttempts) + } + } + service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = true, + ) + repeat(5) { + service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = false, + ) + } + + val publishedEvents = publishedEvents(domainEventPublisher, 3) + assertEquals( + listOf( + PupilStuckThresholdReachedEvent::class, + PupilRecoveredFromStuckEvent::class, + PupilStuckThresholdReachedEvent::class, + ), + publishedEvents.map { it::class }, + ) + } + + @Test + fun `record verified attempt outcome ignores completed stops`() { + val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) + val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) + val record = progress(stopId = 1L, status = StopProgressStatus.COMPLETED, consecutiveWrongAttempts = 5) + + stubFind(progressRepository, record) + + val result = service.recordVerifiedAttemptOutcome( + pupilUserId = 1L, + classroomId = 2L, + stopId = 1L, + correct = false, + ) + + assertEquals(5, result.consecutiveWrongAttempts) + Mockito.verify(progressRepository, Mockito.never()).save(any(PupilStopProgress::class.java)) + Mockito.verifyNoInteractions(domainEventPublisher) } private fun progress( stopId: Long, status: StopProgressStatus = StopProgressStatus.NOT_STARTED, bestScore: Int = 0, + consecutiveWrongAttempts: Int = 0, isFinalBoss: Boolean = false, isActive: Boolean = true, ): PupilStopProgress { @@ -327,9 +528,17 @@ class PupilStopProgressServiceTests { ).apply { this.status = status this.bestScore = bestScore + this.consecutiveWrongAttempts = consecutiveWrongAttempts } } + private fun service( + progressRepository: PupilStopProgressRepository, + mapStopRepository: MapStopsRepository, + domainEventPublisher: DomainEventPublisher = Mockito.mock(DomainEventPublisher::class.java), + ): PupilStopProgressService = + PupilStopProgressService(progressRepository, mapStopRepository, domainEventPublisher) + private fun stubFind(repo: PupilStopProgressRepository, record: PupilStopProgress) { Mockito.`when`(repo.findByIdPupilUserIdAndIdClassroomIdAndIdStopId( record.id.pupilUserId, record.id.classroomId, record.id.stopId, @@ -340,4 +549,16 @@ class PupilStopProgressServiceTests { stubFind(repo, record) Mockito.`when`(repo.save(any(PupilStopProgress::class.java))).thenAnswer { it.arguments[0] } } + + private fun publishedEvents( + domainEventPublisher: DomainEventPublisher, + times: Int, + ): List { + val events = Mockito.mockingDetails(domainEventPublisher).invocations + .filter { invocation -> invocation.method.name == "publish" } + .map { invocation -> invocation.arguments.single() as DomainEvent } + assertEquals(times, events.size) + assertTrue(events.all { event -> event.occurredAt != null }) + return events + } } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt index 36fe4f1c..e924dce0 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt @@ -15,9 +15,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.notification.domain.NotificationRenderCode +import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationMuteRepository import edu.ntnu.idi.idatt.backend.notification.infrastructure.TeacherNotificationRepository import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired @@ -75,7 +78,7 @@ class NotificationEventIntegrationTests { } @Test - fun `client controlled stop completion does not create teacher notifications`() { + fun `client controlled stop completion creates teacher notification`() { val teacher = userRepository.save(activeTeacher("owner-stop-event@example.com")) val pupil = userRepository.save(activePupil("pupil-stop-event")) val classroom = createClassroom("EVENTSTOP1", teacher) @@ -92,7 +95,34 @@ class NotificationEventIntegrationTests { status { isOk() } } - assertEquals(0, teacherNotificationRepository.count()) + val notifications = teacherNotificationRepository.findAll() + assertEquals(1, notifications.size) + assertEquals(NotificationType.MAP_STOP_COMPLETED, notifications.single().type) + assertEquals(NotificationRenderCode.MAP_STOP_COMPLETED.code, notifications.single().renderCode) + } + + @Test + fun `client controlled final boss completion creates stop and game notifications`() { + val teacher = userRepository.save(activeTeacher("owner-game-event@example.com")) + val pupil = userRepository.save(activePupil("pupil-game-event")) + val classroom = createClassroom("EVENTGAME1", teacher) + val stop = createStop("event-final-boss", "Final boss", 1, isFinalBoss = true) + seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) + val pupilToken = pupilAccessToken("pupil-game-event", "secret123") + + mockMvc.patch("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/stop-progress/${stop.id}") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $pupilToken") + content = """{"status":"COMPLETED"}""" + }.andExpect { + status { isOk() } + } + + val notifications = teacherNotificationRepository.findAll() + assertEquals(2, notifications.size) + assertTrue(notifications.any { it.type == NotificationType.MAP_STOP_COMPLETED }) + assertTrue(notifications.any { it.type == NotificationType.GAME_COMPLETED }) } @Test From 9a005e4a01068157dce09c5662e1e122f18d35db Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 10:44:12 +0200 Subject: [PATCH 10/15] Add Kdocs --- .../application/PupilStopProgressService.kt | 37 ++++++++++++++++ .../NotificationDeliveryService.kt | 15 +++++++ .../TeacherNotificationEventListener.kt | 44 +++++++++++++++++++ 3 files changed, 96 insertions(+) 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 ff2668e4..d4fbdf84 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 @@ -107,6 +107,24 @@ class PupilStopProgressService( return progressRepository.save(progress) } + /** + * Records a backend-verified answer outcome for one stop attempt without exposing a public + * pupil-controlled HTTP contract. + * + * Wrong answers increment [PupilStopProgress.consecutiveWrongAttempts] until the stuck + * threshold is crossed, at which point a single [PupilStuckThresholdReachedEvent] is + * published. Correct answers reset the counter and publish + * [PupilRecoveredFromStuckEvent] when they resolve a previously stuck state. + * + * Calls for already completed stops are ignored. + * + * @param pupilUserId pupil whose verified outcome is being recorded + * @param classroomId classroom that scopes the progress record + * @param stopId stop whose attempt outcome was verified by backend-owned logic + * @param correct whether the verified outcome was correct + * @return the updated progress record, or the unchanged record if the stop is already completed + * @throws ResponseStatusException 404 if no progress record exists for the given ids + */ @Transactional fun recordVerifiedAttemptOutcome( pupilUserId: Long, @@ -235,6 +253,16 @@ class PupilStopProgressService( ) } } + + /** + * Clears the stuck-attempt counter when a stop completes and publishes recovery if that + * completion resolves an active stuck state. + * + * @param pupilUserId pupil whose stuck state may be resolved + * @param classroomId classroom that scopes the progress record + * @param stopId stop whose completion may resolve the stuck thread + * @param progress mutable progress record being finalized + */ private fun resolveStuckIfNeeded( pupilUserId: Long, classroomId: Long, @@ -254,6 +282,15 @@ class PupilStopProgressService( } } + /** + * Publishes completion events for a newly completed stop, including the game-completed event + * when the stop is the active final boss. + * + * @param pupilUserId pupil who completed the stop + * @param classroomId classroom that scopes the completion + * @param stopId stop that was completed + * @param progress completed progress record used to determine final-boss behavior + */ private fun publishCompletionEvents( pupilUserId: Long, classroomId: Long, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt index 9d84c0bb..9fff2c46 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt @@ -18,6 +18,13 @@ class NotificationDeliveryService( private val teacherNotificationMuteRepository: TeacherNotificationMuteRepository, private val recipientResolver: ClassroomNotificationRecipientResolver, ) { + /** + * Fans one notification draft out to all teacher recipients for the classroom in a new + * transaction, skipping muted recipients and suppressing duplicate active-thread deliveries. + * + * @param draft notification metadata to fan out + * @return persisted teacher-specific notification rows that were actually created + */ @Transactional(propagation = Propagation.REQUIRES_NEW) fun deliverToClassroomTeachers(draft: NotificationDraft): List { val recipients = recipientResolver.resolveTeacherRecipientIds(draft.classroomId) @@ -61,6 +68,14 @@ class NotificationDeliveryService( return notifications } + /** + * Marks all unresolved notifications for the given classroom/thread as resolved in a new + * transaction and clears their active-thread keys so the thread may reopen later. + * + * @param classroomId classroom that scopes the notification thread + * @param threadKey stable notification thread key to resolve + * @return number of notifications resolved + */ @Transactional(propagation = Propagation.REQUIRES_NEW) fun resolveThread(classroomId: Long, threadKey: String): Int { val now = Instant.now() diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt index 7271f3dd..a950c8c6 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt @@ -18,6 +18,11 @@ class TeacherNotificationEventListener( private val notificationDeliveryService: NotificationDeliveryService, private val notificationEventContextResolver: NotificationEventContextResolver, ) { + /** + * Materializes one teacher inbox notification per recipient after a pupil completes a stop. + * + * @param event committed stop-completion business event + */ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onMapStopCompleted(event: MapStopCompletedEvent) { val context = notificationEventContextResolver.resolveStopContext( @@ -48,6 +53,11 @@ class TeacherNotificationEventListener( ) } + /** + * Materializes one teacher inbox notification per recipient after a pupil completes the game. + * + * @param event committed game-completion business event + */ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onGameCompleted(event: PupilGameCompletedEvent) { val context = notificationEventContextResolver.resolveStopContext( @@ -77,6 +87,12 @@ class TeacherNotificationEventListener( ) } + /** + * Materializes a stuck notification thread once a verified attempt sequence crosses the stuck + * threshold for a stop. + * + * @param event committed stuck-threshold business event + */ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onPupilStuck(event: PupilStuckThresholdReachedEvent) { val context = notificationEventContextResolver.resolveStopContext( @@ -108,6 +124,11 @@ class TeacherNotificationEventListener( ) } + /** + * Resolves the active stuck notification thread after the source stop has recovered. + * + * @param event committed stuck-recovery business event + */ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun onPupilRecovered(event: PupilRecoveredFromStuckEvent) { notificationDeliveryService.resolveThread( @@ -117,12 +138,35 @@ class TeacherNotificationEventListener( } companion object { + /** + * Stable thread key for stop-completion notifications for one pupil/stop/classroom tuple. + * + * @param classroomId classroom that scopes the notification thread + * @param pupilUserId pupil that owns the completion + * @param stopId stop that was completed + * @return deterministic notification thread key + */ fun stopCompletedThreadKey(classroomId: Long, pupilUserId: Long, stopId: Long): String = "stop-completed:$classroomId:$pupilUserId:$stopId" + /** + * Stable thread key for game-completion notifications for one pupil/classroom tuple. + * + * @param classroomId classroom that scopes the notification thread + * @param pupilUserId pupil that completed the game + * @return deterministic notification thread key + */ fun gameCompletedThreadKey(classroomId: Long, pupilUserId: Long): String = "game-completed:$classroomId:$pupilUserId" + /** + * Stable thread key for stuck notifications for one pupil/stop/classroom tuple. + * + * @param classroomId classroom that scopes the notification thread + * @param pupilUserId pupil that is stuck + * @param stopId stop where the pupil is stuck + * @return deterministic notification thread key + */ fun stuckThreadKey(classroomId: Long, pupilUserId: Long, stopId: Long): String = "stuck:$classroomId:$pupilUserId:$stopId" } From 73f6fbb6921a20fa224cc633cf4e162d214da479 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 10:48:20 +0200 Subject: [PATCH 11/15] Prevent updating currentTaskId when progress is completed --- .../game/mapstops/application/PupilStopProgressService.kt | 4 +++- .../backend/game/mapstops/PupilStopProgressServiceTests.kt | 2 +- 2 files changed, 4 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 d4fbdf84..1d8b2843 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 @@ -100,7 +100,9 @@ class PupilStopProgressService( publishCompletionEvents(pupilUserId, classroomId, stopId, progress) } } - command.currentTaskId?.let { progress.currentTaskId = it } + if (progress.status != StopProgressStatus.COMPLETED) { + command.currentTaskId?.let { progress.currentTaskId = it } + } command.bestScore?.let { if (it > progress.bestScore) progress.bestScore = it } command.medalAwarded?.let { progress.medalAwarded = it } 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 a2e6353c..f5b79379 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 @@ -279,7 +279,7 @@ class PupilStopProgressServiceTests { pupilUserId = 1L, classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand( status = StopProgressStatus.COMPLETED, - currentTaskId = null, + currentTaskId = 99L, bestScore = null, medalAwarded = null, ), From fd237458077adaa8968617b855fd6eefca51e884 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 11:24:19 +0200 Subject: [PATCH 12/15] Add more missing KDocs --- .../api/NotificationApiMappings.kt | 21 +++++++ .../api/NotificationController.kt | 55 +++++++++++++++++++ .../api/NotificationMuteResponse.kt | 7 +++ .../api/NotificationPageResponse.kt | 9 +++ .../notification/api/NotificationResponse.kt | 15 +++++ .../api/NotificationSummaryResponse.kt | 5 ++ .../ClassroomNotificationRecipientResolver.kt | 7 +++ .../NotificationEventContextResolver.kt | 22 ++++++++ .../application/NotificationInboxService.kt | 41 ++++++++++++++ .../application/NotificationMuteService.kt | 21 +++++++ .../application/NotificationPage.kt | 9 +++ .../application/NotificationSummary.kt | 5 ++ .../TeacherNotificationMuteRepository.kt | 25 +++++++++ .../TeacherNotificationRepository.kt | 41 +++++++++++++- 14 files changed, 282 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt index 3af7c392..9b84b38a 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt @@ -5,6 +5,12 @@ import edu.ntnu.idi.idatt.backend.notification.application.NotificationSummary import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute +/** + * Maps a persisted teacher notification to the API response contract. + * + * @return API representation of this inbox item. + * @throws IllegalArgumentException if the notification has not been persisted yet. + */ fun TeacherNotification.toResponse(): NotificationResponse = NotificationResponse( id = requireNotNull(id) { "Notification is missing an id" }, @@ -20,6 +26,11 @@ fun TeacherNotification.toResponse(): NotificationResponse = createdAt = createdAt, ) +/** + * Maps one inbox page from the application layer to the API response contract. + * + * @return API representation of this page of notifications. + */ fun NotificationPage.toResponse(): NotificationPageResponse = NotificationPageResponse( items = items.map(TeacherNotification::toResponse), @@ -29,11 +40,21 @@ fun NotificationPage.toResponse(): NotificationPageResponse = totalPages = totalPages, ) +/** + * Maps inbox summary data to the API response contract. + * + * @return API representation of the inbox summary counters. + */ fun NotificationSummary.toResponse(): NotificationSummaryResponse = NotificationSummaryResponse( unreadCount = unreadCount, ) +/** + * Maps a persisted mute preference to the API response contract. + * + * @return API representation of this mute preference. + */ fun TeacherNotificationMute.toResponse(): NotificationMuteResponse = NotificationMuteResponse( classroomId = classroomId, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt index f39d2cc2..b6dbb453 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt @@ -14,12 +14,26 @@ import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController +/** + * Exposes the teacher notification inbox and mute preference endpoints. + */ @RestController @RequestMapping("/api/v1/users/me/notifications") class NotificationController( private val notificationInboxService: NotificationInboxService, private val notificationMuteService: NotificationMuteService, ) { + /** + * Returns one page of inbox notifications for the authenticated teacher. + * + * @param currentUser authenticated teacher or admin principal. + * @param classroomId optional classroom filter. + * @param type optional notification type filter. + * @param unreadOnly when `true`, only unread notifications are returned. + * @param page zero-based page index. + * @param size requested page size. + * @return paged notification response for the authenticated teacher. + */ @GetMapping fun getNotifications( @AuthenticationPrincipal currentUser: CurrentUser, @@ -33,12 +47,25 @@ class NotificationController( .getInbox(currentUser.subject, classroomId, type, unreadOnly, page, size) .toResponse() + /** + * Returns inbox counters for the authenticated teacher. + * + * @param currentUser authenticated teacher or admin principal. + * @return summary containing unread notification counts. + */ @GetMapping("/summary") fun getNotificationSummary( @AuthenticationPrincipal currentUser: CurrentUser, ): NotificationSummaryResponse = notificationInboxService.getSummary(currentUser.subject).toResponse() + /** + * Marks one notification as read for the authenticated teacher. + * + * @param currentUser authenticated teacher or admin principal. + * @param notificationId notification identifier in the personal inbox. + * @return updated notification state. + */ @PatchMapping("/{notificationId}/read") fun markNotificationRead( @AuthenticationPrincipal currentUser: CurrentUser, @@ -46,6 +73,13 @@ class NotificationController( ): NotificationResponse = notificationInboxService.markRead(currentUser.subject, notificationId).toResponse() + /** + * Dismisses one notification from the authenticated teacher's inbox. + * + * @param currentUser authenticated teacher or admin principal. + * @param notificationId notification identifier in the personal inbox. + * @return updated notification state. + */ @PatchMapping("/{notificationId}/dismiss") fun dismissNotification( @AuthenticationPrincipal currentUser: CurrentUser, @@ -53,6 +87,12 @@ class NotificationController( ): NotificationResponse = notificationInboxService.dismiss(currentUser.subject, notificationId).toResponse() + /** + * Lists active mute preferences for the authenticated teacher. + * + * @param currentUser authenticated teacher or admin principal. + * @return mute preferences owned by the authenticated teacher. + */ @GetMapping("/mutes") fun getMutes( @AuthenticationPrincipal currentUser: CurrentUser, @@ -61,6 +101,14 @@ class NotificationController( .listMutes(currentUser.subject) .map { mute -> mute.toResponse() } + /** + * Creates or keeps a mute preference for one classroom and notification type. + * + * @param currentUser authenticated teacher or admin principal. + * @param classroomId classroom to mute notifications for. + * @param type notification type to mute. + * @return the active mute preference after the operation. + */ @PutMapping("/mutes/{classroomId}/{type}") fun mute( @AuthenticationPrincipal currentUser: CurrentUser, @@ -69,6 +117,13 @@ class NotificationController( ): NotificationMuteResponse = notificationMuteService.mute(currentUser.subject, classroomId, type).toResponse() + /** + * Removes one mute preference for the authenticated teacher. + * + * @param currentUser authenticated teacher or admin principal. + * @param classroomId classroom to unmute notifications for. + * @param type notification type to unmute. + */ @DeleteMapping("/mutes/{classroomId}/{type}") fun unmute( @AuthenticationPrincipal currentUser: CurrentUser, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt index 526320e0..8681014d 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt @@ -3,6 +3,13 @@ package edu.ntnu.idi.idatt.backend.notification.api import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import java.time.Instant +/** + * API response describing one active teacher mute preference. + * + * @property classroomId muted classroom identifier. + * @property type muted notification type. + * @property createdAt when the mute preference was created. + */ data class NotificationMuteResponse( val classroomId: Long, val type: NotificationType, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt index 074ef567..4efd1a82 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt @@ -1,5 +1,14 @@ package edu.ntnu.idi.idatt.backend.notification.api +/** + * API response for one page of teacher inbox notifications. + * + * @property items notifications on the requested page. + * @property page zero-based page index. + * @property size page size actually returned. + * @property totalElements total number of matching notifications. + * @property totalPages total number of available pages. + */ data class NotificationPageResponse( val items: List, val page: Int, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt index 3f198b0a..6e1ea016 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt @@ -3,6 +3,21 @@ package edu.ntnu.idi.idatt.backend.notification.api import edu.ntnu.idi.idatt.backend.notification.domain.NotificationType import java.time.Instant +/** + * API response for one teacher inbox notification. + * + * @property id notification identifier in the teacher's inbox. + * @property classroomId classroom that produced the notification. + * @property pupilUserId related pupil identifier when applicable. + * @property type stable notification type for filtering and mute logic. + * @property renderCode frontend render key for localized message rendering. + * @property renderArgsJson frontend render arguments serialized as JSON. + * @property payloadJson optional structured payload for deep links or UI behavior. + * @property readAt when the notification was marked as read. + * @property dismissedAt when the notification was dismissed from the inbox. + * @property resolvedAt when the underlying thread or condition was resolved. + * @property createdAt when the notification row was created. + */ data class NotificationResponse( val id: Long, val classroomId: Long, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt index 99488d5a..a35c203c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt @@ -1,5 +1,10 @@ package edu.ntnu.idi.idatt.backend.notification.api +/** + * API response with inbox counters for the authenticated teacher. + * + * @property unreadCount number of unread, non-dismissed notifications. + */ data class NotificationSummaryResponse( val unreadCount: Long, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt index 562cfe81..fe31ec1c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt @@ -12,6 +12,13 @@ import org.springframework.web.server.ResponseStatusException class ClassroomNotificationRecipientResolver( private val classroomRepository: ClassroomRepository, ) { + /** + * Resolves all teacher recipients that administer the given classroom. + * + * @param classroomId classroom whose owner and teacher memberships should receive notifications. + * @return deduplicated teacher user ids for the classroom. + * @throws ResponseStatusException if the classroom does not exist. + */ fun resolveTeacherRecipientIds(classroomId: Long): Set { val classroom = classroomRepository.findById(classroomId) .orElseThrow { diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt index 792b8dbc..be814be2 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt @@ -9,6 +9,13 @@ import org.springframework.http.HttpStatus import org.springframework.stereotype.Component import org.springframework.web.server.ResponseStatusException +/** + * Snapshot of stop-related display data needed to render a teacher notification. + * + * @property classroomTitle classroom title shown in the notification UI. + * @property pupilDisplayName pupil name shown in the notification UI. + * @property stopTitle stop title shown in the notification UI. + */ data class StopNotificationContext( val classroomTitle: String, val pupilDisplayName: String, @@ -27,6 +34,15 @@ class NotificationEventContextResolver( ) { private val objectMapper = JsonMapper.builder().build() + /** + * Resolves the classroom, pupil, and stop display fields for one stop-based event. + * + * @param classroomId classroom related to the event. + * @param pupilUserId pupil related to the event. + * @param stopId stop related to the event. + * @return resolved display data for notification rendering. + * @throws ResponseStatusException if any referenced domain object is missing. + */ fun resolveStopContext( classroomId: Long, pupilUserId: Long, @@ -53,6 +69,12 @@ class NotificationEventContextResolver( ) } + /** + * Serializes a small ordered key-value payload to JSON for frontend rendering arguments. + * + * @param entries ordered key-value pairs to serialize. + * @return JSON object string containing the provided entries. + */ fun json(vararg entries: Pair): String = objectMapper.writeValueAsString(linkedMapOf(*entries)) } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt index ed0f234e..65d58182 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt @@ -19,6 +19,17 @@ class NotificationInboxService( private val teacherNotificationRepository: TeacherNotificationRepository, private val currentUserResolver: CurrentUserResolver, ) { + /** + * Returns one page of inbox items for the authenticated teacher. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @param classroomId optional classroom filter. + * @param type optional notification type filter. + * @param unreadOnly when `true`, only unread notifications are returned. + * @param page zero-based page index. + * @param size requested page size, clamped to supported bounds. + * @return paged inbox view for the teacher. + */ @Transactional(readOnly = true) fun getInbox( authenticatedSubject: String, @@ -49,6 +60,12 @@ class NotificationInboxService( ) } + /** + * Returns unread counters for the authenticated teacher's inbox. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @return summary counters for the inbox badge. + */ @Transactional(readOnly = true) fun getSummary(authenticatedSubject: String): NotificationSummary { val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) @@ -58,6 +75,14 @@ class NotificationInboxService( ) } + /** + * Marks one inbox item as read for the authenticated teacher. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @param notificationId teacher-owned notification identifier. + * @return updated notification entity. + * @throws ResponseStatusException if the notification does not belong to the teacher. + */ @Transactional fun markRead( authenticatedSubject: String, @@ -70,6 +95,14 @@ class NotificationInboxService( return teacherNotificationRepository.save(notification) } + /** + * Dismisses one inbox item for the authenticated teacher and marks it read if needed. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @param notificationId teacher-owned notification identifier. + * @return updated notification entity. + * @throws ResponseStatusException if the notification does not belong to the teacher. + */ @Transactional fun dismiss( authenticatedSubject: String, @@ -86,6 +119,14 @@ class NotificationInboxService( return teacherNotificationRepository.save(notification) } + /** + * Resolves one teacher-owned notification or fails with `404`. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @param notificationId teacher-owned notification identifier. + * @return matching notification entity. + * @throws ResponseStatusException if the notification is not found for the teacher. + */ private fun requireTeacherNotification( authenticatedSubject: String, notificationId: Long, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt index e37f1bcc..99216eff 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt @@ -17,6 +17,12 @@ class NotificationMuteService( private val currentUserResolver: CurrentUserResolver, private val classroomUserResolver: ClassroomUserResolver, ) { + /** + * Lists active mute preferences for the authenticated teacher. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @return mute preferences owned by the teacher. + */ @Transactional(readOnly = true) fun listMutes(authenticatedSubject: String): List { val teacher = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) @@ -24,6 +30,14 @@ class NotificationMuteService( return teacherNotificationMuteRepository.findAllByTeacherUserIdOrderByClassroomIdAscTypeAsc(teacherId) } + /** + * Creates one mute preference if it does not already exist. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @param classroomId classroom to mute notifications for. + * @param type notification type to mute. + * @return existing or newly created mute preference. + */ @Transactional fun mute( authenticatedSubject: String, @@ -52,6 +66,13 @@ class NotificationMuteService( ) } + /** + * Removes one mute preference if it exists. + * + * @param authenticatedSubject authenticated teacher or admin subject. + * @param classroomId classroom to unmute notifications for. + * @param type notification type to unmute. + */ @Transactional fun unmute( authenticatedSubject: String, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt index 34d3cf60..d6f6da3f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt @@ -2,6 +2,15 @@ package edu.ntnu.idi.idatt.backend.notification.application import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotification +/** + * Application-layer page of teacher inbox notifications. + * + * @property items notifications on the requested page. + * @property page zero-based page index. + * @property size page size actually returned. + * @property totalElements total number of matching notifications. + * @property totalPages total number of available pages. + */ data class NotificationPage( val items: List, val page: Int, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt index e69b818f..41a462b8 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt @@ -1,5 +1,10 @@ package edu.ntnu.idi.idatt.backend.notification.application +/** + * Application-layer inbox counters for one teacher. + * + * @property unreadCount number of unread, non-dismissed notifications. + */ data class NotificationSummary( val unreadCount: Long, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt index 18d08af5..9528abd3 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt @@ -5,16 +5,41 @@ import edu.ntnu.idi.idatt.backend.notification.domain.TeacherNotificationMute import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository +/** + * Repository for teacher notification mute preferences. + */ @Repository interface TeacherNotificationMuteRepository : JpaRepository { + /** + * Checks whether one mute preference already exists. + * + * @param teacherUserId teacher who owns the mute preference. + * @param classroomId muted classroom identifier. + * @param type muted notification type. + * @return `true` when the mute preference exists. + */ fun existsByTeacherUserIdAndClassroomIdAndType( teacherUserId: Long, classroomId: Long, type: NotificationType, ): Boolean + /** + * Returns all mute preferences for one teacher in a stable classroom/type order. + * + * @param teacherUserId teacher who owns the mute preferences. + * @return mute preferences owned by the teacher. + */ fun findAllByTeacherUserIdOrderByClassroomIdAscTypeAsc(teacherUserId: Long): List + /** + * Finds one mute preference for one teacher, classroom, and notification type. + * + * @param teacherUserId teacher who owns the mute preference. + * @param classroomId muted classroom identifier. + * @param type muted notification type. + * @return matching mute preference, or `null` when absent. + */ fun findByTeacherUserIdAndClassroomIdAndType( teacherUserId: Long, classroomId: Long, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt index 3e13219b..edec3d09 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt @@ -9,9 +9,21 @@ import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.query.Param import org.springframework.stereotype.Repository +/** + * Repository for persisted teacher inbox notifications. + */ @Repository interface TeacherNotificationRepository : JpaRepository { - + /** + * Returns one filtered inbox page for one teacher. + * + * @param teacherUserId teacher whose personal inbox should be queried. + * @param classroomId optional classroom filter. + * @param type optional notification type filter. + * @param unreadOnly when `true`, only unread notifications are returned. + * @param pageable requested page and sort information. + * @return matching inbox page excluding dismissed notifications. + */ @Query( """ SELECT notification @@ -32,10 +44,30 @@ interface TeacherNotificationRepository : JpaRepository + /** + * Counts unread, non-dismissed inbox items for one teacher. + * + * @param teacherUserId teacher whose inbox should be counted. + * @return unread notification count. + */ fun countByTeacherUserIdAndReadAtIsNullAndDismissedAtIsNull(teacherUserId: Long): Long + /** + * Finds one notification only if it belongs to the given teacher. + * + * @param id notification identifier. + * @param teacherUserId teacher who owns the notification. + * @return matching notification, or `null` when absent. + */ fun findByIdAndTeacherUserId(id: Long, teacherUserId: Long): TeacherNotification? + /** + * Returns unresolved notifications in one thread for one teacher. + * + * @param teacherUserId teacher who owns the inbox rows. + * @param threadKey logical notification thread identifier. + * @return unresolved notifications for that teacher and thread. + */ @Query( """ SELECT notification @@ -51,6 +83,13 @@ interface TeacherNotificationRepository : JpaRepository + /** + * Returns unresolved notifications for one classroom thread across all teachers. + * + * @param classroomId classroom that owns the thread. + * @param threadKey logical notification thread identifier. + * @return unresolved notifications matching the classroom thread. + */ fun findAllByClassroomIdAndThreadKeyAndResolvedAtIsNull( classroomId: Long, threadKey: String, From b9b7d3843885dfcbbdbeb873d2817f14c5531577 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 11:46:35 +0200 Subject: [PATCH 13/15] See if this flyway fix fixes the CI tests --- src/test/resources/application.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 97e22ea6..02b93912 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -3,6 +3,7 @@ spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.flyway.enabled=true +spring.flyway.locations=filesystem:src/main/resources/db/migration spring.jpa.hibernate.ddl-auto=validate app.security.jwt.issuer=https://test.nettdetektivene.local/backend From 735cc982db39a65a877fa0a3f3ecb5516b485bc4 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 11:54:24 +0200 Subject: [PATCH 14/15] Revert "See if this flyway fix fixes the CI tests" This reverts commit b9b7d3843885dfcbbdbeb873d2817f14c5531577. --- src/test/resources/application.properties | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 02b93912..97e22ea6 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -3,7 +3,6 @@ spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.flyway.enabled=true -spring.flyway.locations=filesystem:src/main/resources/db/migration spring.jpa.hibernate.ddl-auto=validate app.security.jwt.issuer=https://test.nettdetektivene.local/backend From 9886428fb3f98a4fe2edd5d72952b5d68afbdfd2 Mon Sep 17 00:00:00 2001 From: Johannes Aamot-Skeidsvoll Date: Thu, 23 Apr 2026 11:55:20 +0200 Subject: [PATCH 15/15] Update migration versions --- ...ions_table.sql => V18__create_teacher_notifications_table.sql} | 0 ...table.sql => V19__create_teacher_notification_mutes_table.sql} | 0 ...20__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename src/main/resources/db/migration/{V16__create_teacher_notifications_table.sql => V18__create_teacher_notifications_table.sql} (100%) rename src/main/resources/db/migration/{V17__create_teacher_notification_mutes_table.sql => V19__create_teacher_notification_mutes_table.sql} (100%) rename src/main/resources/db/migration/{V18__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql => V20__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql} (100%) diff --git a/src/main/resources/db/migration/V16__create_teacher_notifications_table.sql b/src/main/resources/db/migration/V18__create_teacher_notifications_table.sql similarity index 100% rename from src/main/resources/db/migration/V16__create_teacher_notifications_table.sql rename to src/main/resources/db/migration/V18__create_teacher_notifications_table.sql diff --git a/src/main/resources/db/migration/V17__create_teacher_notification_mutes_table.sql b/src/main/resources/db/migration/V19__create_teacher_notification_mutes_table.sql similarity index 100% rename from src/main/resources/db/migration/V17__create_teacher_notification_mutes_table.sql rename to src/main/resources/db/migration/V19__create_teacher_notification_mutes_table.sql diff --git a/src/main/resources/db/migration/V18__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql b/src/main/resources/db/migration/V20__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql similarity index 100% rename from src/main/resources/db/migration/V18__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql rename to src/main/resources/db/migration/V20__add_consecutive_wrong_attempts_to_pupil_stop_progress.sql