Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions docs/notifications-architecture.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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,
) {

/**
Expand Down Expand Up @@ -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")

Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
override val occurredAt: Instant = Instant.now(),
) : DomainEvent
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ fun MapStopOverviewEntry.toResponse(): MapStopOverviewResponse =
status = status,
stars = stars,
medalAwarded = medalAwarded,
)
)
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ class PupilProgressSeedingEventListener(
classroom = event.classroom,
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
}
Loading