diff --git a/docs/notifications-architecture.md b/docs/notifications-architecture.md new file mode 100644 index 00000000..f1e1afc5 --- /dev/null +++ b/docs/notifications-architecture.md @@ -0,0 +1,136 @@ +# 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` +- `thread_key` +- `active_thread_key` +- `render_code` +- `render_args_json` +- `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 wired producers: + +- 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: + +- `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` as a backend-owned signal +reserved for future verified gameplay integration. + +## 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}` + +`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 + +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 and include a stable `threadKey` when the + notification represents an active state that may be reopened or resolved. +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. +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/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index c746cad5..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 @@ -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, ) { /** @@ -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") @@ -138,7 +134,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..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 @@ -46,4 +46,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/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 61fde0ac..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 @@ -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,7 +24,8 @@ import java.time.Instant @Service class PupilStopProgressService( private val progressRepository: PupilStopProgressRepository, - private val mapStopRepository: MapStopsRepository + private val mapStopRepository: MapStopsRepository, + private val domainEventPublisher: DomainEventPublisher, ) { /** * Returns all stop progress records for a pupil in a classroom. @@ -87,18 +93,83 @@ class PupilStopProgressService( progress.status = next if (next == StopProgressStatus.COMPLETED && progress.completedAt == null) { + resolveStuckIfNeeded(pupilUserId, classroomId, stopId, progress) progress.currentTaskId = null progress.completedAt = Instant.now() unlockNextStop(pupilUserId, classroomId, stopId, activeStops) + 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 } 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, + 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. @@ -184,4 +255,70 @@ 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, + stopId: Long, + progress: PupilStopProgress, + ) { + val wasStuck = progress.consecutiveWrongAttempts >= STUCK_THRESHOLD + progress.consecutiveWrongAttempts = 0 + if (wasStuck) { + domainEventPublisher.publish( + PupilRecoveredFromStuckEvent( + pupilUserId = pupilUserId, + classroomId = classroomId, + stopId = stopId, + ), + ) + } + } + + /** + * 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, + 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/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/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..9b84b38a --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationApiMappings.kt @@ -0,0 +1,63 @@ +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 + +/** + * 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" }, + classroomId = classroomId, + pupilUserId = pupilUserId, + type = type, + renderCode = renderCode, + renderArgsJson = renderArgsJson, + payloadJson = payloadJson, + readAt = readAt, + dismissedAt = dismissedAt, + resolvedAt = resolvedAt, + 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), + page = page, + size = size, + totalElements = totalElements, + 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, + 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..b6dbb453 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationController.kt @@ -0,0 +1,135 @@ +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 + +/** + * 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, + @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() + + /** + * 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, + @PathVariable notificationId: Long, + ): 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, + @PathVariable notificationId: Long, + ): 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, + ): List = + notificationMuteService + .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, + @PathVariable classroomId: Long, + @PathVariable type: NotificationType, + ): 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, + @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..8681014d --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationMuteResponse.kt @@ -0,0 +1,17 @@ +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, + 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..4efd1a82 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationPageResponse.kt @@ -0,0 +1,18 @@ +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, + 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..6e1ea016 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationResponse.kt @@ -0,0 +1,33 @@ +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, + val pupilUserId: Long?, + val type: NotificationType, + val renderCode: String, + val renderArgsJson: 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..a35c203c --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/api/NotificationSummaryResponse.kt @@ -0,0 +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 new file mode 100644 index 00000000..fe31ec1c --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/ClassroomNotificationRecipientResolver.kt @@ -0,0 +1,35 @@ +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, +) { + /** + * 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 { + 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..9fff2c46 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDeliveryService.kt @@ -0,0 +1,98 @@ +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.Propagation +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, +) { + /** + * 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) + val notifications = mutableListOf() + + recipients.forEach { teacherUserId -> + val isMuted = teacherNotificationMuteRepository.existsByTeacherUserIdAndClassroomIdAndType( + teacherUserId = teacherUserId, + classroomId = draft.classroomId, + type = draft.type, + ) + if (isMuted) { + return@forEach + } + + val notification = TeacherNotification( + teacherUserId = teacherUserId, + classroomId = draft.classroomId, + pupilUserId = draft.pupilUserId, + type = draft.type, + threadKey = draft.threadKey, + activeThreadKey = draft.threadKey, + renderCode = draft.renderCode.code, + renderArgsJson = draft.renderArgsJson, + 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 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() + val activeNotifications = teacherNotificationRepository.findAllByClassroomIdAndThreadKeyAndResolvedAtIsNull( + classroomId = classroomId, + threadKey = threadKey, + ) + + if (activeNotifications.isEmpty()) { + return 0 + } + + 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/application/NotificationDraft.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt new file mode 100644 index 00000000..e443ad2f --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationDraft.kt @@ -0,0 +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 + +/** + * 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 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 new file mode 100644 index 00000000..be814be2 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationEventContextResolver.kt @@ -0,0 +1,80 @@ +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 + +/** + * 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, + val stopTitle: String, +) + +/** + * Resolves domain context needed to build teacher notification render arguments. + */ +@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() + + /** + * 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, + 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", + ) + } + + /** + * 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 new file mode 100644 index 00000000..65d58182 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationInboxService.kt @@ -0,0 +1,139 @@ +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, +) { + /** + * 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, + 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, + ) + } + + /** + * 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) + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + return NotificationSummary( + unreadCount = teacherNotificationRepository.countByTeacherUserIdAndReadAtIsNullAndDismissedAtIsNull(teacherId), + ) + } + + /** + * 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, + notificationId: Long, + ): TeacherNotification { + val notification = requireTeacherNotification(authenticatedSubject, notificationId) + if (notification.readAt == null) { + notification.readAt = Instant.now() + } + 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, + 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) + } + + /** + * 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, + ): 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..99216eff --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationMuteService.kt @@ -0,0 +1,92 @@ +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, +) { + /** + * 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) + val teacherId = requireNotNull(teacher.id) { "Authenticated teacher is missing an id" } + 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, + 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, + ), + ) + } + + /** + * 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, + 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..d6f6da3f --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationPage.kt @@ -0,0 +1,20 @@ +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, + 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..41a462b8 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/NotificationSummary.kt @@ -0,0 +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/application/TeacherNotificationEventListener.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt new file mode 100644 index 00000000..a950c8c6 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/application/TeacherNotificationEventListener.kt @@ -0,0 +1,173 @@ +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 +import edu.ntnu.idi.idatt.backend.shared.events.PupilRecoveredFromStuckEvent +import edu.ntnu.idi.idatt.backend.shared.events.PupilStuckThresholdReachedEvent +import org.springframework.stereotype.Component +import org.springframework.transaction.event.TransactionPhase +import org.springframework.transaction.event.TransactionalEventListener + +/** + * Translates business events into teacher inbox notifications. + */ +@Component +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( + 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, + threadKey = threadKey, + 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, + ), + ), + ) + } + + /** + * 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( + 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, + threadKey = threadKey, + 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, + ), + ), + ) + } + + /** + * 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( + 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, + threadKey = threadKey, + 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, + ), + ), + ) + } + + /** + * 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( + classroomId = event.classroomId, + threadKey = stuckThreadKey(event.classroomId, event.pupilUserId, event.stopId), + ) + } + + 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" + } +} 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/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..24bbb0cc --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/domain/TeacherNotification.kt @@ -0,0 +1,55 @@ +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, + @Column(name = "thread_key", length = 255) + var threadKey: String? = null, + @Column(name = "active_thread_key", length = 255) + var activeThreadKey: String? = null, + @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") + 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..9528abd3 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationMuteRepository.kt @@ -0,0 +1,48 @@ +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 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, + 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..edec3d09 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notification/infrastructure/TeacherNotificationRepository.kt @@ -0,0 +1,97 @@ +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 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 + 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 + + /** + * 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 + 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 + + /** + * 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, + ): 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/V18__create_teacher_notifications_table.sql b/src/main/resources/db/migration/V18__create_teacher_notifications_table.sql new file mode 100644 index 00000000..87aac659 --- /dev/null +++ b/src/main/resources/db/migration/V18__create_teacher_notifications_table.sql @@ -0,0 +1,35 @@ +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, + thread_key VARCHAR(255), + active_thread_key VARCHAR(255), + render_code VARCHAR(255) NOT NULL, + render_args_json TEXT, + 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, + CONSTRAINT uk_teacher_notifications_active_thread + UNIQUE (teacher_user_id, active_thread_key) +); + +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/V19__create_teacher_notification_mutes_table.sql b/src/main/resources/db/migration/V19__create_teacher_notification_mutes_table.sql new file mode 100644 index 00000000..34a9741d --- /dev/null +++ b/src/main/resources/db/migration/V19__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/main/resources/db/migration/V20__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 new file mode 100644 index 00000000..504935a6 --- /dev/null +++ b/src/main/resources/db/migration/V20__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 8a0481f6..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 @@ -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,8 @@ class PupilStopProgressServiceTests { fun `update progress clears current task id when stop completes`() { val progressRepository = Mockito.mock(PupilStopProgressRepository::class.java) val mapStopRepository = Mockito.mock(MapStopsRepository::class.java) - val service = PupilStopProgressService(progressRepository, mapStopRepository) + val domainEventPublisher = Mockito.mock(DomainEventPublisher::class.java) + val service = service(progressRepository, mapStopRepository, domainEventPublisher) val record = progress(stopId = 1L, status = StopProgressStatus.IN_PROGRESS).apply { currentTaskId = 7L } @@ -260,7 +279,7 @@ class PupilStopProgressServiceTests { pupilUserId = 1L, classroomId = 2L, stopId = 1L, command = UpdateStopProgressCommand( status = StopProgressStatus.COMPLETED, - currentTaskId = null, + currentTaskId = 99L, bestScore = null, medalAwarded = null, ), @@ -273,7 +292,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) @@ -290,7 +309,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) @@ -303,12 +323,216 @@ 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 and publishes game completed event`() { + 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 = 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), + ) + + 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 { val pupil = User( id = 1L, @@ -317,7 +541,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), @@ -327,9 +555,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 +576,15 @@ 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/NotificationControllerIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt new file mode 100644 index 00000000..c24a7af9 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationControllerIntegrationTests.kt @@ -0,0 +1,338 @@ +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.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 +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("$.items[0].renderCode") { value(NotificationRenderCode.MAP_STOP_COMPLETED.code) } + 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")) + 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, + threadKey = if (type == NotificationType.PUPIL_STUCK) "stuck:$classroomId:$teacherUserId" else null, + activeThreadKey = if (type == NotificationType.PUPIL_STUCK) "stuck:$classroomId:$teacherUserId" else null, + 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( + 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..e87356f7 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationDeliveryServiceTests.kt @@ -0,0 +1,143 @@ +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 +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.ArgumentMatchers.any +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` + +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 duplicate active thread recipients`() { + val draft = NotificationDraft( + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + threadKey = "stuck:42:7:3", + renderCode = NotificationRenderCode.PUPIL_STUCK, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", + 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.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, + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", + ), + ), + ) + + val savedNotifications = notificationDeliveryService.deliverToClassroomTeachers(draft) + + assertEquals(1, savedNotifications.size) + assertEquals(10L, savedNotifications.single().teacherUserId) + verify(teacherNotificationRepository, times(2)).saveAndFlush(any(TeacherNotification::class.java)) + } + + @Test + fun `resolve thread marks matching notifications as resolved`() { + val unresolvedFirst = TeacherNotification( + id = 1L, + teacherUserId = 10L, + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", + ) + val unresolvedSecond = TeacherNotification( + id = 2L, + teacherUserId = 11L, + classroomId = 42L, + pupilUserId = 7L, + type = NotificationType.PUPIL_STUCK, + threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", + ) + `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) + 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 new file mode 100644 index 00000000..e924dce0 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationEventIntegrationTests.kt @@ -0,0 +1,214 @@ +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.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 +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 `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) + 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() } + } + + 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 + 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) + val stop = createStop("event-stuck-stop", "Stuck stop", 1) + seedProgress(pupil, classroom, stop, StopProgressStatus.IN_PROGRESS) + val pupilToken = pupilAccessToken("pupil-stuck-event", "secret123") + + 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":false}""" + }.andExpect { + status { isNotFound() } + } + + assertEquals(0, teacherNotificationRepository.count()) + } + + 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 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/NotificationInboxServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt new file mode 100644 index 00000000..767a00f7 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationInboxServiceTests.kt @@ -0,0 +1,106 @@ +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.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 +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, + threadKey = "stuck:42:7:3", + activeThreadKey = "stuck:42:7:3", + 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 new file mode 100644 index 00000000..74f5bc80 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notification/NotificationPersistenceTests.kt @@ -0,0 +1,233 @@ +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.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 +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, + threadKey = "stuck:1:2:3", + activeThreadKey = "stuck:1:2:3", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", + payloadJson = """{"stopId":3}""", + ), + ) + + 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) + } + + @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, + threadKey = "stuck:1:2:3", + activeThreadKey = "stuck:1:2:3", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", + ), + ) + + assertThrows { + teacherNotificationRepository.saveAndFlush( + TeacherNotification( + teacherUserId = requireNotNull(teacher.id), + classroomId = classroom.id, + pupilUserId = null, + type = NotificationType.PUPIL_STUCK, + threadKey = "stuck:1:2:3", + activeThreadKey = "stuck:1:2:3", + renderCode = NotificationRenderCode.PUPIL_STUCK.code, + renderArgsJson = """{"stopTitle":"Omrade 3"}""", + ), + ) + } + } + + @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, + threadKey = null, + activeThreadKey = null, + 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( + 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, + ), + ) + } +}