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
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,10 @@ class DevDataBootstrap(
) {
val activeStopsBySlug = stops.associateBy { requireNotNull(it.slug) { "Seeded map stop must have a slug" } }

stops.forEach { stop ->
seedGameNotebookEntriesForStop(classroom, stop)
}

activeStopsBySlug["nyhetskvartalet"]?.let { stop ->
seedNotebookEntry(
pupil = pupilAda,
Expand All @@ -366,16 +370,6 @@ class DevDataBootstrap(
content = "Ada la merke til at overskriften brukte sterke følelser og manglet tydelige kilder.",
)
}
activeStopsBySlug["postkontoret"]?.let { stop ->
seedNotebookEntry(
pupil = pupilAda,
classroom = classroom,
stop = stop,
sourceType = NotebookSourceType.GAME,
title = "Phishing-tegn",
content = "Spillet markerte dårlig språk, hastverk og mistenkelig lenke som tydelige faresignaler.",
)
}
activeStopsBySlug["fotografen"]?.let { stop ->
seedNotebookEntry(
pupil = pupilNoah,
Expand All @@ -388,23 +382,50 @@ class DevDataBootstrap(
}
}

private fun seedGameNotebookEntriesForStop(
classroom: Classroom,
stop: MapStop,
) {
val stopTitle = requireNotNull(stop.title) { "Seeded map stop must have a title" }
val notebookEntries = listOf(
"Hva vi oppdaget" to "Spillet oppsummerte de viktigste sporene fra $stopTitle og viste hvilke detaljer som burde undersøkes nærmere.",
"Tegn å passe på" to "Notatet fra $stopTitle fremhevet faresignaler som uklar avsender, manglende kontekst eller forsøk på å skape stress.",
"Huskeliste" to "Spillet foreslo å dobbeltsjekke kilder, sammenligne informasjon og ta vare på bevis før man går videre fra $stopTitle.",
)

notebookEntries.forEach { (title, content) ->
seedNotebookEntry(
pupil = null,
classroom = classroom,
stop = stop,
sourceType = NotebookSourceType.GAME,
title = title,
content = content,
)
}
}

private fun seedNotebookEntry(
pupil: User,
pupil: User?,
classroom: Classroom,
stop: MapStop,
sourceType: NotebookSourceType,
title: String,
content: String,
) {
val pupilId = requireNotNull(pupil.id) { "Pupil seed user must have an id" }
val classroomId = classroom.id
val stopId = requireNotNull(stop.id) { "Seeded map stop must have an id" }
val existingEntry = notebookEntryRepository.findAllByPupilId(pupilId).firstOrNull {
it.classroom.id == classroomId && it.stop.id == stopId && it.title == title
val existingEntry = notebookEntryRepository.findAll().firstOrNull {
it.classroom.id == classroomId &&
it.stop.id == stopId &&
it.title == title &&
it.sourceType == sourceType &&
it.pupil?.id == pupil?.id
}
if (existingEntry != null) {
existingEntry.sourceType = sourceType
existingEntry.content = content
existingEntry.pupil = pupil
return
}
notebookEntryRepository.save(
Expand All @@ -423,4 +444,4 @@ class DevDataBootstrap(
HexFormat.of().formatHex(
MessageDigest.getInstance("SHA-256").digest(rawToken.toByteArray(StandardCharsets.UTF_8)),
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookEntry
fun NotebookEntry.toResponse(): NotebookEntryResponse =
NotebookEntryResponse(
id = requireNotNull(id) { "Notebook entry is missing an id" },
pupilUserId = requireNotNull(pupil.id) { "Notebook entry pupil is missing an id" },
pupilUserId = pupil?.id,
classroomId = classroom.id,
stopId = requireNotNull(stop.id) { "Notebook entry stop is missing an id" },
sourceType = sourceType.name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import java.time.Instant
* Serialized notebook entry returned by notebook endpoints.
*
* @property id notebook entry identifier
* @property pupilUserId owner pupil user id
* @property pupilUserId owner pupil user id when the entry originates from a pupil
* @property classroomId classroom id for the entry context
* @property stopId map stop id for the entry context
* @property sourceType serialized notebook source type
Expand All @@ -17,7 +17,7 @@ import java.time.Instant
*/
data class NotebookEntryResponse(
val id: Long,
val pupilUserId: Long,
val pupilUserId: Long?,
val classroomId: Long,
val stopId: Long,
val sourceType: String,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package edu.ntnu.idi.idatt.backend.notebook.application

import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository
import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository
import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver
import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser
import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookEntry
import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType
import edu.ntnu.idi.idatt.backend.notebook.infrastructure.NotebookEntryRepository
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
Expand All @@ -22,6 +24,7 @@ class NotebookService(
private val notebookEntryRepository: NotebookEntryRepository,
private val currentUserResolver: CurrentUserResolver,
private val mapStopsRepository: MapStopsRepository,
private val pupilGameProgressRepository: PupilGameProgressRepository,
) {
/**
* Returns all notebook entries owned by the authenticated pupil.
Expand All @@ -33,7 +36,14 @@ class NotebookService(
fun getAllNotebookEntries(currentUser: CurrentUser): List<NotebookEntry> {
val pupil = currentUserResolver.requirePupil(currentUser.subject)
val pupilId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" }
return notebookEntryRepository.findAllByPupilId(pupilId)

val classroom = currentUserResolver.getClassroomByUser(currentUser)
val classroomId = requireNotNull(classroom.id) { "Active classroom is missing an id" }

val gameProgress = pupilGameProgressRepository.findByPupilIdAndClassroomId(pupilId, classroomId)
val completedStopsCount = gameProgress?.completedStopsCount ?: 0

return notebookEntryRepository.findAllVisibleToPupil(pupilId, classroomId, completedStopsCount)
}

/**
Expand All @@ -47,6 +57,10 @@ class NotebookService(
val pupil = currentUserResolver.requirePupil(command.currentUser.subject)
val classroom = currentUserResolver.getClassroomByUser(command.currentUser)

if (command.sourceType == NotebookSourceType.GAME) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot create notes with sourceType set to GAME")
}

if (classroom.id != command.classroomId) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot create notebook entries outside the active classroom")
}
Expand All @@ -57,7 +71,7 @@ class NotebookService(
}

val notebookEntry = NotebookEntry(
pupil = pupil,
pupil = if (command.sourceType == NotebookSourceType.PUPIL) pupil else null,
classroom = classroom,
stop = stop,
sourceType = command.sourceType,
Expand Down Expand Up @@ -93,6 +107,7 @@ class NotebookService(
fun deleteNotebookEntry(command: DeleteNotebookEntryCommand) {
val pupil = currentUserResolver.requirePupil(command.currentUser.subject)
val notebookEntry = verifyOwnership(pupil.id, command.notebookEntryId)

notebookEntryRepository.delete(notebookEntry)
}

Expand All @@ -110,7 +125,11 @@ class NotebookService(
ResponseStatusException(HttpStatus.NOT_FOUND, "Notebook entry not found")
}

val ownerId = requireNotNull(notebookEntry.pupil.id) { "Notebook entry pupil is missing an id" }
if (notebookEntry.sourceType == NotebookSourceType.GAME) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot create notebook entries outside the active classroom")
}

val ownerId = notebookEntry.pupil?.id
if (ownerId != resolvedPupilId) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot access another pupil's notebook entry")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.PrePersist
import jakarta.persistence.PreUpdate
import jakarta.persistence.Table
import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.UpdateTimestamp
Expand All @@ -22,7 +24,7 @@ import java.time.Instant
* Persisted notebook entry created for a pupil within a classroom and map stop context.
*
* @property id Database identifier.
* @property pupil Pupil that owns the notebook entry.
* @property pupil Pupil that owns the notebook entry when the source type is [NotebookSourceType.PUPIL].
* @property classroom Classroom the notebook entry belongs to.
* @property stop Map stop the notebook entry is associated with.
* @property sourceType Source that produced the entry content.
Expand All @@ -37,9 +39,9 @@ class NotebookEntry(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null,
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "pupil_user_id", nullable = false)
var pupil: User,
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "pupil_user_id", nullable = true)
var pupil: User?,
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "classroom_id", nullable = false)
var classroom: Classroom,
Expand All @@ -59,4 +61,18 @@ class NotebookEntry(
@UpdateTimestamp
@Column(name = "updated_at", nullable = false)
var updatedAt: Instant? = null,
)
) {
@PrePersist
@PreUpdate
fun validatePupilOwnership() {
when (sourceType) {
NotebookSourceType.GAME -> require(pupil == null) {
"Notebook entries with source type GAME must not reference a pupil"
}

NotebookSourceType.PUPIL -> requireNotNull(pupil) {
"Notebook entries with source type PUPIL must reference a pupil"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package edu.ntnu.idi.idatt.backend.notebook.infrastructure

import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookEntry
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository

/**
Expand All @@ -11,10 +12,22 @@ import org.springframework.stereotype.Repository
interface NotebookEntryRepository : JpaRepository<NotebookEntry, Long> {

/**
* Finds all entries owned by a given pupil
* Finds all notebook entries visible to a pupil:
* - pupil-authored entries owned by the pupil
* - game-authored entries for the pupil's active classroom
*
* @param pupilId the id of the pupil
* @return all entries connected to the pupil
* @param classroomId the id of the active classroom
* @return all visible notebook entries
*/
fun findAllByPupilId(pupilId: Long): List<NotebookEntry>
@Query(
"""
select notebookEntry
from NotebookEntry notebookEntry
where (notebookEntry.pupil.id = :pupilId
or (notebookEntry.pupil is null and notebookEntry.classroom.id = :classroomId))
and notebookEntry.stop.displayOrder <= :completedStops + 1
"""
)
fun findAllVisibleToPupil(pupilId: Long, classroomId: Long, completedStops: Int): List<NotebookEntry>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
ALTER TABLE notebook_entries
MODIFY COLUMN pupil_user_id BIGINT NULL;

UPDATE notebook_entries
SET pupil_user_id = NULL
WHERE source_type = 'GAME';

ALTER TABLE notebook_entries
ADD CONSTRAINT chk_notebook_entries_source_type_pupil
CHECK (
(source_type = 'GAME' AND pupil_user_id IS NULL) OR
(source_type = 'PUPIL' AND pupil_user_id IS NOT NULL)
);
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class NotebookEntryControllerIntegrationTests {
Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A")
)
val stop = mapStopsRepository.save(
MapStop(slug = "intro", title = "Intro")
MapStop(slug = "intro", title = "Intro", displayOrder = 1)
)
val pupil = userRepository.save(activePupil("ada"))
val otherPupil = userRepository.save(activePupil("grace"))
Expand Down Expand Up @@ -127,7 +127,7 @@ class NotebookEntryControllerIntegrationTests {
Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A")
)
val stop = mapStopsRepository.save(
MapStop(slug = "intro", title = "Intro")
MapStop(slug = "intro", title = "Intro", displayOrder = 1)
)
val pupil = userRepository.save(activePupil("ada"))
pupilProfileRepository.save(PupilProfile(user = pupil, displayName = "Ada", currentClassroomId = classroom.id))
Expand Down Expand Up @@ -169,7 +169,7 @@ class NotebookEntryControllerIntegrationTests {
Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A")
)
val stop = mapStopsRepository.save(
MapStop(slug = "intro", title = "Intro")
MapStop(slug = "intro", title = "Intro", displayOrder = 1)
)
val pupil = userRepository.save(activePupil("ada"))
pupilProfileRepository.save(PupilProfile(user = pupil, displayName = "Ada", currentClassroomId = classroom.id))
Expand Down Expand Up @@ -208,7 +208,7 @@ class NotebookEntryControllerIntegrationTests {
Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A")
)
val stop = mapStopsRepository.save(
MapStop(slug = "intro", title = "Intro")
MapStop(slug = "intro", title = "Intro", displayOrder = 1)
)
val pupil = userRepository.save(activePupil("ada"))
val otherPupil = userRepository.save(activePupil("grace"))
Expand Down
Loading