From e89059cf91b36b53676c02ee0c5396727e7007b4 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 09:42:24 +0200 Subject: [PATCH 01/13] add NotebookEntry class Signed-off-by: sindrelm --- .../backend/notebook/domain/NotebookEntry.kt | 64 +++++++++++++++++++ .../notebook/domain/NotebookSourceType.kt | 6 ++ 2 files changed, 70 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookSourceType.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt new file mode 100644 index 00000000..f1b597b6 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt @@ -0,0 +1,64 @@ +package edu.ntnu.idi.idatt.backend.notebook.domain + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop +import edu.ntnu.idi.idatt.backend.iam.domain.User +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.EnumType +import jakarta.persistence.Enumerated +import jakarta.persistence.FetchType +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.JoinColumn +import jakarta.persistence.Lob +import jakarta.persistence.ManyToOne +import jakarta.persistence.Table +import org.hibernate.annotations.CreationTimestamp +import org.hibernate.annotations.UpdateTimestamp +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 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. + * @property title Short entry title. + * @property content Full notebook entry body. + * @property createdAt Timestamp when the row was created. + * @property updatedAt Timestamp when the row was last updated. + */ +@Entity +@Table(name = "notebook_entries") +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 = false) + @JoinColumn(name = "classroom_id", nullable = false) + var classroom: Classroom, + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "stop_id", nullable = false) + var stop: MapStop, + @Enumerated(EnumType.STRING) + @Column(name = "source_type", nullable = false) + var sourceType: NotebookSourceType, + @Column(name = "title", nullable = false) + var title: String, + @Lob + @Column(name = "content", nullable = false) + var content: String, + @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/notebook/domain/NotebookSourceType.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookSourceType.kt new file mode 100644 index 00000000..07611e69 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookSourceType.kt @@ -0,0 +1,6 @@ +package edu.ntnu.idi.idatt.backend.notebook.domain + +enum class NotebookSourceType { + GAME, + PUPIL, +} \ No newline at end of file From 124867f8fc2d15d9f7227f60e45fee984f3e93c1 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 09:47:46 +0200 Subject: [PATCH 02/13] add NotebookEntryRepository Signed-off-by: sindrelm --- .../infrastructure/NotebookEntryRepository.kt | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt new file mode 100644 index 00000000..e112ffd7 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt @@ -0,0 +1,12 @@ +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.stereotype.Repository + +/** + * Repository for persisted [NotebookEntry] entities. + */ +@Repository +interface NotebookEntryRepository : JpaRepository { +} From dbfd72885282b259b8504321abce1479a6bb613e Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 09:53:14 +0200 Subject: [PATCH 03/13] add getAllByPupilId method Signed-off-by: sindrelm --- .../notebook/infrastructure/NotebookEntryRepository.kt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt index e112ffd7..ee42fc4e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt @@ -9,4 +9,12 @@ import org.springframework.stereotype.Repository */ @Repository interface NotebookEntryRepository : JpaRepository { + + /** + * Finds all entries owned by a given pupil + * + * @param pupilUserId the id of the pupil + * @return all entries connected to the pupil + */ + fun getAllByPupilUserId(pupilUserId: Long) : List } From 7bd11cd9a16b898af4edff990ef9189d6c2efa4f Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 10:21:47 +0200 Subject: [PATCH 04/13] Add application layer commands Signed-off-by: sindrelm --- .../application/CreateNotebookEntryCommand.kt | 24 +++++++++++++++++++ .../application/DeleteNotebookEntryCommand.kt | 14 +++++++++++ .../application/UpdateNotebookEntryCommand.kt | 18 ++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt new file mode 100644 index 00000000..76bb88bc --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt @@ -0,0 +1,24 @@ +package edu.ntnu.idi.idatt.backend.notebook.application + +import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType + +/** + * Command representing the intent to create a notebook entry. + * + * This is part of the application layer and should not depend on HTTP or framework-specific classes. + * + * @property authenticatedSubject JWT subject for the authenticated pupil creating the entry. + * @property classroomId Identifier of the classroom the entry belongs to. + * @property stopId Identifier of the map stop the entry belongs to. + * @property sourceType Source that produced the notebook entry. + * @property title Short notebook entry title. + * @property content Full notebook entry body. + */ +data class CreateNotebookEntryCommand( + val authenticatedSubject: String, + val classroomId: Long, + val stopId: Long, + val sourceType: NotebookSourceType, + val title: String, + val content: String, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt new file mode 100644 index 00000000..6845da3b --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt @@ -0,0 +1,14 @@ +package edu.ntnu.idi.idatt.backend.notebook.application + +/** + * Command representing the intent to delete an existing notebook entry. + * + * This is part of the application layer and should not depend on HTTP or framework-specific classes. + * + * @property authenticatedSubject JWT subject for the authenticated pupil deleting the entry. + * @property notebookEntryId Identifier of the notebook entry being deleted. + */ +data class DeleteNotebookEntryCommand( + val authenticatedSubject: String, + val notebookEntryId: Long, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt new file mode 100644 index 00000000..a1e5a3de --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt @@ -0,0 +1,18 @@ +package edu.ntnu.idi.idatt.backend.notebook.application + +/** + * Command representing the intent to update an existing notebook entry. + * + * This is part of the application layer and should not depend on HTTP or framework-specific classes. + * + * @property authenticatedSubject JWT subject for the authenticated pupil updating the entry. + * @property notebookEntryId Identifier of the notebook entry being updated. + * @property title Updated notebook entry title. + * @property content Updated notebook entry body. + */ +data class UpdateNotebookEntryCommand( + val authenticatedSubject: String, + val notebookEntryId: Long, + val title: String, + val content: String, +) From 38f51a0ed3681304ad373152b10c8b8234a0a202 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:00:13 +0200 Subject: [PATCH 05/13] Add NotebookService class Signed-off-by: sindrelm --- .../application/CreateNotebookEntryCommand.kt | 5 +- .../application/DeleteNotebookEntryCommand.kt | 6 +- .../notebook/application/NotebookService.kt | 89 +++++++++++++++++++ .../application/UpdateNotebookEntryCommand.kt | 6 +- .../infrastructure/NotebookEntryRepository.kt | 4 +- 5 files changed, 102 insertions(+), 8 deletions(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt index 76bb88bc..d7bf0fc6 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/CreateNotebookEntryCommand.kt @@ -1,5 +1,6 @@ package edu.ntnu.idi.idatt.backend.notebook.application +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType /** @@ -7,7 +8,7 @@ import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType * * This is part of the application layer and should not depend on HTTP or framework-specific classes. * - * @property authenticatedSubject JWT subject for the authenticated pupil creating the entry. + * @property currentUser authenticated user creating the entry. * @property classroomId Identifier of the classroom the entry belongs to. * @property stopId Identifier of the map stop the entry belongs to. * @property sourceType Source that produced the notebook entry. @@ -15,7 +16,7 @@ import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType * @property content Full notebook entry body. */ data class CreateNotebookEntryCommand( - val authenticatedSubject: String, + val currentUser: CurrentUser, val classroomId: Long, val stopId: Long, val sourceType: NotebookSourceType, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt index 6845da3b..ba153af4 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/DeleteNotebookEntryCommand.kt @@ -1,14 +1,16 @@ package edu.ntnu.idi.idatt.backend.notebook.application +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser + /** * Command representing the intent to delete an existing notebook entry. * * This is part of the application layer and should not depend on HTTP or framework-specific classes. * - * @property authenticatedSubject JWT subject for the authenticated pupil deleting the entry. + * @property currentUser authenticated user deleting the entry. * @property notebookEntryId Identifier of the notebook entry being deleted. */ data class DeleteNotebookEntryCommand( - val authenticatedSubject: String, + val currentUser: CurrentUser, val notebookEntryId: Long, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt new file mode 100644 index 00000000..676e888c --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt @@ -0,0 +1,89 @@ +package edu.ntnu.idi.idatt.backend.notebook.application + +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.infrastructure.NotebookEntryRepository +import org.springframework.http.HttpStatus +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import org.springframework.web.server.ResponseStatusException + +@Service +class NotebookService( + private val notebookEntryRepository: NotebookEntryRepository, + private val currentUserResolver: CurrentUserResolver, + private val mapStopsRepository: MapStopsRepository, +) { + + @Transactional(readOnly = true) + fun getAllNotebookEntries(currentUser: CurrentUser): List { + val pupil = currentUserResolver.requirePupil(currentUser.subject) + val pupilId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" } + return notebookEntryRepository.findAllByPupilId(pupilId) + } + + @Transactional + fun createNotebookEntry(command: CreateNotebookEntryCommand): NotebookEntry { + val pupil = currentUserResolver.requirePupil(command.currentUser.subject) + val classroom = currentUserResolver.getClassroomByUser(command.currentUser) + + if (classroom.id != command.classroomId) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot create notebook entries outside the active classroom") + } + + val stop = mapStopsRepository.findById(command.stopId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Map stop not found") + } + + val notebookEntry = NotebookEntry( + pupil = pupil, + classroom = classroom, + stop = stop, + sourceType = command.sourceType, + title = command.title, + content = command.content, + ) + return notebookEntryRepository.save(notebookEntry) + } + + @Transactional + fun updateNotebookEntry(command: UpdateNotebookEntryCommand): NotebookEntry { + val pupil = currentUserResolver.requirePupil(command.currentUser.subject) + val pupilId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" } + + val notebookEntry = notebookEntryRepository.findById(command.notebookEntryId).orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Notebook entry not found") + } + + val ownerId = requireNotNull(notebookEntry.pupil.id) { "Notebook entry pupil is missing an id" } + if (ownerId != pupilId) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot update another pupil's notebook entry") + } + + notebookEntry.title = command.title + notebookEntry.content = command.content + + return notebookEntryRepository.save(notebookEntry) + } + + @Transactional + fun deleteNotebookEntry(command: DeleteNotebookEntryCommand) { + val pupil = currentUserResolver.requirePupil(command.currentUser.subject) + val pupilId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" } + + val notebookEntry = notebookEntryRepository.findById(command.notebookEntryId).orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Notebook entry not found") + } + + val ownerId = requireNotNull(notebookEntry.pupil.id) { "Notebook entry pupil is missing an id" } + if (ownerId != pupilId) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot delete another pupil's notebook entry") + } + + + notebookEntryRepository.delete(notebookEntry) + } +} \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt index a1e5a3de..930c3c9e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/UpdateNotebookEntryCommand.kt @@ -1,17 +1,19 @@ package edu.ntnu.idi.idatt.backend.notebook.application +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser + /** * Command representing the intent to update an existing notebook entry. * * This is part of the application layer and should not depend on HTTP or framework-specific classes. * - * @property authenticatedSubject JWT subject for the authenticated pupil updating the entry. + * @property currentUser authenticated user updating the entry. * @property notebookEntryId Identifier of the notebook entry being updated. * @property title Updated notebook entry title. * @property content Updated notebook entry body. */ data class UpdateNotebookEntryCommand( - val authenticatedSubject: String, + val currentUser: CurrentUser, val notebookEntryId: Long, val title: String, val content: String, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt index ee42fc4e..4e249031 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/infrastructure/NotebookEntryRepository.kt @@ -13,8 +13,8 @@ interface NotebookEntryRepository : JpaRepository { /** * Finds all entries owned by a given pupil * - * @param pupilUserId the id of the pupil + * @param pupilId the id of the pupil * @return all entries connected to the pupil */ - fun getAllByPupilUserId(pupilUserId: Long) : List + fun findAllByPupilId(pupilId: Long): List } From 94ad6c6be2782f8c74118e9f75b2f03af7fc7a47 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:04:38 +0200 Subject: [PATCH 06/13] Add notebook api endpoints Signed-off-by: sindrelm --- .../notebook/api/NotebookEntryApiMappings.kt | 59 ++++++++++++++++ .../notebook/api/NotebookEntryController.kt | 68 +++++++++++++++++++ .../notebook/api/NotebookEntryRequests.kt | 32 +++++++++ .../notebook/api/NotebookEntryResponses.kt | 18 +++++ 4 files changed, 177 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt new file mode 100644 index 00000000..1f99fb66 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt @@ -0,0 +1,59 @@ +package edu.ntnu.idi.idatt.backend.notebook.api + +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import edu.ntnu.idi.idatt.backend.notebook.application.CreateNotebookEntryCommand +import edu.ntnu.idi.idatt.backend.notebook.application.DeleteNotebookEntryCommand +import edu.ntnu.idi.idatt.backend.notebook.application.UpdateNotebookEntryCommand +import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookEntry + +/** + * Converts a notebook entry entity into the public API response payload. + */ +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" }, + classroomId = classroom.id, + stopId = requireNotNull(stop.id) { "Notebook entry stop is missing an id" }, + sourceType = sourceType.name, + title = title, + content = content, + createdAt = createdAt, + updatedAt = updatedAt, + ) + +/** + * Converts the create request payload into an application command. + */ +fun CreateNotebookEntryRequest.toCommand(currentUser: CurrentUser): CreateNotebookEntryCommand = + CreateNotebookEntryCommand( + currentUser = currentUser, + classroomId = classroomId, + stopId = stopId, + sourceType = sourceType, + title = title, + content = content, + ) + +/** + * Converts the update request payload into an application command. + */ +fun UpdateNotebookEntryRequest.toCommand( + currentUser: CurrentUser, + notebookEntryId: Long, +): UpdateNotebookEntryCommand = + UpdateNotebookEntryCommand( + currentUser = currentUser, + notebookEntryId = notebookEntryId, + title = title, + content = content, + ) + +/** + * Converts the authenticated principal and path id into a delete command. + */ +fun CurrentUser.toDeleteCommand(notebookEntryId: Long): DeleteNotebookEntryCommand = + DeleteNotebookEntryCommand( + currentUser = this, + notebookEntryId = notebookEntryId, + ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt new file mode 100644 index 00000000..d1946bc5 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt @@ -0,0 +1,68 @@ +package edu.ntnu.idi.idatt.backend.notebook.api + +import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser +import edu.ntnu.idi.idatt.backend.notebook.application.NotebookService +import jakarta.validation.Valid +import org.springframework.http.HttpStatus +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.PathVariable +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.PutMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.ResponseStatus +import org.springframework.web.bind.annotation.RestController + +/** + * REST API for the authenticated pupil's notebook entries. + */ +@RestController +@RequestMapping("/api/v1/users/me/notebook-entries") +class NotebookEntryController( + private val notebookService: NotebookService, +) { + /** + * Returns all notebook entries owned by the authenticated pupil. + */ + @GetMapping + fun getNotebookEntries( + @AuthenticationPrincipal currentUser: CurrentUser, + ): List = + notebookService.getAllNotebookEntries(currentUser).map { it.toResponse() } + + /** + * Creates a new notebook entry for the authenticated pupil. + */ + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + fun createNotebookEntry( + @AuthenticationPrincipal currentUser: CurrentUser, + @Valid @RequestBody request: CreateNotebookEntryRequest, + ): NotebookEntryResponse = + notebookService.createNotebookEntry(request.toCommand(currentUser)).toResponse() + + /** + * Updates one notebook entry owned by the authenticated pupil. + */ + @PutMapping("/{notebookEntryId}") + fun updateNotebookEntry( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable notebookEntryId: Long, + @Valid @RequestBody request: UpdateNotebookEntryRequest, + ): NotebookEntryResponse = + notebookService.updateNotebookEntry(request.toCommand(currentUser, notebookEntryId)).toResponse() + + /** + * Deletes one notebook entry owned by the authenticated pupil. + */ + @DeleteMapping("/{notebookEntryId}") + @ResponseStatus(HttpStatus.NO_CONTENT) + fun deleteNotebookEntry( + @AuthenticationPrincipal currentUser: CurrentUser, + @PathVariable notebookEntryId: Long, + ) { + notebookService.deleteNotebookEntry(currentUser.toDeleteCommand(notebookEntryId)) + } +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt new file mode 100644 index 00000000..780e58fc --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt @@ -0,0 +1,32 @@ +package edu.ntnu.idi.idatt.backend.notebook.api + +import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotBlank +import jakarta.validation.constraints.NotNull + +/** + * Request payload for creating a notebook entry. + */ +data class CreateNotebookEntryRequest( + @field:Min(1) + val classroomId: Long, + @field:Min(1) + val stopId: Long, + @field:NotNull + val sourceType: NotebookSourceType, + @field:NotBlank + val title: String, + @field:NotBlank + val content: String, +) + +/** + * Request payload for updating a notebook entry. + */ +data class UpdateNotebookEntryRequest( + @field:NotBlank + val title: String, + @field:NotBlank + val content: String, +) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt new file mode 100644 index 00000000..d1bfc3b3 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt @@ -0,0 +1,18 @@ +package edu.ntnu.idi.idatt.backend.notebook.api + +import java.time.Instant + +/** + * Serialized notebook entry returned by notebook endpoints. + */ +data class NotebookEntryResponse( + val id: Long, + val pupilUserId: Long, + val classroomId: Long, + val stopId: Long, + val sourceType: String, + val title: String, + val content: String, + val createdAt: Instant?, + val updatedAt: Instant?, +) From 61f0d84d25185ba82430674146478be7188b61e6 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:09:46 +0200 Subject: [PATCH 07/13] Add notebook related tests Signed-off-by: sindrelm --- ...NotebookEntryControllerIntegrationTests.kt | 281 +++++++++++++++++ .../backend/notebook/NotebookServiceTests.kt | 283 ++++++++++++++++++ 2 files changed, 564 insertions(+) create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookEntryControllerIntegrationTests.kt create mode 100644 src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookEntryControllerIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookEntryControllerIntegrationTests.kt new file mode 100644 index 00000000..423196d7 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookEntryControllerIntegrationTests.kt @@ -0,0 +1,281 @@ +package edu.ntnu.idi.idatt.backend.notebook + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.json.JsonMapper +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +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.infrastructure.MapStopsRepository +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.notebook.domain.NotebookEntry +import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType +import edu.ntnu.idi.idatt.backend.notebook.infrastructure.NotebookEntryRepository +import edu.ntnu.idi.idatt.backend.users.profile.domain.PupilProfile +import edu.ntnu.idi.idatt.backend.users.profile.infrastructure.PupilProfileRepository +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.delete +import org.springframework.test.web.servlet.get +import org.springframework.test.web.servlet.post +import org.springframework.test.web.servlet.put + +@SpringBootTest +@AutoConfigureMockMvc +class NotebookEntryControllerIntegrationTests { + @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 notebookEntryRepository: NotebookEntryRepository + + @Autowired + private lateinit var pupilProfileRepository: PupilProfileRepository + + @Autowired + private lateinit var refreshTokenRepository: RefreshTokenRepository + + @Autowired + private lateinit var passwordEncoder: PasswordEncoder + + private val jsonMapper = JsonMapper.builder().build() + + @BeforeEach + fun setUp() { + refreshTokenRepository.deleteAll() + notebookEntryRepository.deleteAll() + pupilProfileRepository.deleteAll() + mapStopsRepository.deleteAll() + classroomRepository.deleteAll() + userRepository.deleteAll() + } + + @Test + fun `authenticated pupil lists own notebook entries`() { + val teacher = userRepository.save(activeTeacher()) + val classroom = classroomRepository.save( + Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A") + ) + val stop = mapStopsRepository.save( + MapStop(slug = "intro", title = "Intro") + ) + val pupil = userRepository.save(activePupil("ada")) + val otherPupil = userRepository.save(activePupil("grace")) + pupilProfileRepository.save(PupilProfile(user = pupil, displayName = "Ada", currentClassroomId = classroom.id)) + pupilProfileRepository.save(PupilProfile(user = otherPupil, displayName = "Grace", currentClassroomId = classroom.id)) + notebookEntryRepository.save( + NotebookEntry( + pupil = pupil, + classroom = classroom, + stop = stop, + sourceType = NotebookSourceType.PUPIL, + title = "My note", + content = "Visible to owner", + ), + ) + notebookEntryRepository.save( + NotebookEntry( + pupil = otherPupil, + classroom = classroom, + stop = stop, + sourceType = NotebookSourceType.PUPIL, + title = "Other note", + content = "Should not be returned", + ), + ) + val accessToken = pupilAccessToken("ada", "secret123") + + val body = readJson( + mockMvc.get("/api/v1/users/me/notebook-entries") { + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isOk() } + }.andReturn().response.contentAsString, + ) + + assertEquals(1, body.size()) + assertEquals("My note", body[0].get("title").asText()) + assertEquals(requireNotNull(pupil.id), body[0].get("pupilUserId").asLong()) + } + + @Test + fun `authenticated pupil creates notebook entry`() { + val teacher = userRepository.save(activeTeacher()) + val classroom = classroomRepository.save( + Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A") + ) + val stop = mapStopsRepository.save( + MapStop(slug = "intro", title = "Intro") + ) + val pupil = userRepository.save(activePupil("ada")) + pupilProfileRepository.save(PupilProfile(user = pupil, displayName = "Ada", currentClassroomId = classroom.id)) + val accessToken = pupilAccessToken("ada", "secret123") + + val body = readJson( + mockMvc.post("/api/v1/users/me/notebook-entries") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + contentType = MediaType.APPLICATION_JSON + content = + """ + { + "classroomId": ${classroom.id}, + "stopId": ${stop.id}, + "sourceType": "PUPIL", + "title": "Field note", + "content": "Remember this clue" + } + """.trimIndent() + }.andExpect { + status { isCreated() } + jsonPath("$.title") { value("Field note") } + jsonPath("$.content") { value("Remember this clue") } + jsonPath("$.classroomId") { value(classroom.id) } + jsonPath("$.stopId") { value(stop.id) } + jsonPath("$.sourceType") { value("PUPIL") } + }.andReturn().response.contentAsString, + ) + + assertEquals(1, notebookEntryRepository.findAll().size) + assertEquals("Field note", body.get("title").asText()) + } + + @Test + fun `authenticated pupil updates own notebook entry`() { + val teacher = userRepository.save(activeTeacher()) + val classroom = classroomRepository.save( + Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A") + ) + val stop = mapStopsRepository.save( + MapStop(slug = "intro", title = "Intro") + ) + val pupil = userRepository.save(activePupil("ada")) + pupilProfileRepository.save(PupilProfile(user = pupil, displayName = "Ada", currentClassroomId = classroom.id)) + val entry = notebookEntryRepository.save( + NotebookEntry( + pupil = pupil, + classroom = classroom, + stop = stop, + sourceType = NotebookSourceType.PUPIL, + title = "Old title", + content = "Old content", + ), + ) + val accessToken = pupilAccessToken("ada", "secret123") + + mockMvc.put("/api/v1/users/me/notebook-entries/${entry.id}") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + contentType = MediaType.APPLICATION_JSON + content = """{"title":"New title","content":"New content"}""" + }.andExpect { + status { isOk() } + jsonPath("$.title") { value("New title") } + jsonPath("$.content") { value("New content") } + } + + val persisted = notebookEntryRepository.findById(requireNotNull(entry.id)).orElseThrow() + assertEquals("New title", persisted.title) + assertEquals("New content", persisted.content) + } + + @Test + fun `authenticated pupil cannot delete another pupils notebook entry`() { + val teacher = userRepository.save(activeTeacher()) + val classroom = classroomRepository.save( + Classroom(ownerTeacherId = requireNotNull(teacher.id), title = "Class A") + ) + val stop = mapStopsRepository.save( + MapStop(slug = "intro", title = "Intro") + ) + val pupil = userRepository.save(activePupil("ada")) + val otherPupil = userRepository.save(activePupil("grace")) + pupilProfileRepository.save(PupilProfile(user = pupil, displayName = "Ada", currentClassroomId = classroom.id)) + pupilProfileRepository.save(PupilProfile(user = otherPupil, displayName = "Grace", currentClassroomId = classroom.id)) + val entry = notebookEntryRepository.save( + NotebookEntry( + pupil = otherPupil, + classroom = classroom, + stop = stop, + sourceType = NotebookSourceType.PUPIL, + title = "Other title", + content = "Other content", + ), + ) + val accessToken = pupilAccessToken("ada", "secret123") + + mockMvc.delete("/api/v1/users/me/notebook-entries/${entry.id}") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $accessToken") + }.andExpect { + status { isForbidden() } + } + + assertTrue(notebookEntryRepository.findById(requireNotNull(entry.id)).isPresent) + } + + @Test + fun `notebook endpoints require authentication`() { + mockMvc.get("/api/v1/users/me/notebook-entries") + .andExpect { + status { isUnauthorized() } + } + + mockMvc.post("/api/v1/users/me/notebook-entries") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + content = """{"classroomId":1,"stopId":1,"sourceType":"PUPIL","title":"A","content":"B"}""" + }.andExpect { + status { isUnauthorized() } + } + } + + private fun readJson(content: String): JsonNode = jsonMapper.readTree(content) + + private fun pupilAccessToken(username: String, password: String): String = + readJson( + 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 activePupil(username: String) = User( + username = username, + passwordHash = requireNotNull(passwordEncoder.encode("secret123")), + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + + private fun activeTeacher() = User( + email = "teacher@example.com", + passwordHash = requireNotNull(passwordEncoder.encode("secret123")), + role = UserRole.TEACHER, + status = UserStatus.ACTIVE, + ) +} diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt new file mode 100644 index 00000000..a10a5b49 --- /dev/null +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/notebook/NotebookServiceTests.kt @@ -0,0 +1,283 @@ +package edu.ntnu.idi.idatt.backend.notebook + +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop +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.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.security.CurrentUser +import edu.ntnu.idi.idatt.backend.notebook.application.CreateNotebookEntryCommand +import edu.ntnu.idi.idatt.backend.notebook.application.DeleteNotebookEntryCommand +import edu.ntnu.idi.idatt.backend.notebook.application.NotebookService +import edu.ntnu.idi.idatt.backend.notebook.application.UpdateNotebookEntryCommand +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.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.mockito.ArgumentCaptor +import org.mockito.Mockito +import org.springframework.http.HttpStatus +import org.springframework.web.server.ResponseStatusException +import java.util.Optional + +class NotebookServiceTests { + @Test + fun `get all notebook entries returns persisted rows for authenticated pupil`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val entries = listOf(notebookEntry(1L, pupil), notebookEntry(2L, pupil)) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(notebookEntryRepository.findAllByPupilId(42L)).thenReturn(entries) + + val result = service.getAllNotebookEntries(currentUser) + + assertSame(entries, result) + } + + @Test + fun `create notebook entry persists resolved pupil classroom and stop`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val classroom = classroom(7L) + val stop = stop(9L) + val command = CreateNotebookEntryCommand( + currentUser = currentUser, + classroomId = 7L, + stopId = 9L, + sourceType = NotebookSourceType.PUPIL, + title = "My clue", + content = "Important note", + ) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(currentUserResolver.getClassroomByUser(currentUser)).thenReturn(classroom) + Mockito.`when`(mapStopsRepository.findById(9L)).thenReturn(Optional.of(stop)) + Mockito.`when`(notebookEntryRepository.save(Mockito.any(NotebookEntry::class.java))) + .thenAnswer { it.arguments[0] as NotebookEntry } + + val result = service.createNotebookEntry(command) + val captor = ArgumentCaptor.forClass(NotebookEntry::class.java) + Mockito.verify(notebookEntryRepository).save(captor.capture()) + val saved = captor.value + + assertSame(pupil, saved.pupil) + assertSame(classroom, saved.classroom) + assertSame(stop, saved.stop) + assertEquals(NotebookSourceType.PUPIL, saved.sourceType) + assertEquals("My clue", saved.title) + assertEquals("Important note", saved.content) + assertSame(saved, result) + } + + @Test + fun `create notebook entry rejects classroom outside active classroom`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val classroom = classroom(7L) + val command = CreateNotebookEntryCommand( + currentUser = currentUser, + classroomId = 99L, + stopId = 9L, + sourceType = NotebookSourceType.PUPIL, + title = "My clue", + content = "Important note", + ) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(currentUserResolver.getClassroomByUser(currentUser)).thenReturn(classroom) + + val exception = assertThrows { + service.createNotebookEntry(command) + } + + assertEquals(HttpStatus.FORBIDDEN, exception.statusCode) + } + + @Test + fun `create notebook entry rejects unknown stop`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val classroom = classroom(7L) + val command = CreateNotebookEntryCommand( + currentUser = currentUser, + classroomId = 7L, + stopId = 9L, + sourceType = NotebookSourceType.GAME, + title = "Auto note", + content = "Generated note", + ) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(currentUserResolver.getClassroomByUser(currentUser)).thenReturn(classroom) + Mockito.`when`(mapStopsRepository.findById(9L)).thenReturn(Optional.empty()) + + val exception = assertThrows { + service.createNotebookEntry(command) + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + } + + @Test + fun `update notebook entry updates owned row`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val existing = notebookEntry(15L, pupil).apply { + title = "Old title" + content = "Old content" + } + val command = UpdateNotebookEntryCommand( + currentUser = currentUser, + notebookEntryId = 15L, + title = "New title", + content = "New content", + ) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(notebookEntryRepository.findById(15L)).thenReturn(Optional.of(existing)) + Mockito.`when`(notebookEntryRepository.save(existing)).thenReturn(existing) + + val result = service.updateNotebookEntry(command) + + assertEquals("New title", existing.title) + assertEquals("New content", existing.content) + assertSame(existing, result) + } + + @Test + fun `update notebook entry rejects other pupils entry`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val existing = notebookEntry(15L, pupilUser(99L)) + val command = UpdateNotebookEntryCommand( + currentUser = currentUser, + notebookEntryId = 15L, + title = "New title", + content = "New content", + ) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(notebookEntryRepository.findById(15L)).thenReturn(Optional.of(existing)) + + val exception = assertThrows { + service.updateNotebookEntry(command) + } + + assertEquals(HttpStatus.FORBIDDEN, exception.statusCode) + } + + @Test + fun `delete notebook entry deletes owned row`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val existing = notebookEntry(15L, pupil) + val command = DeleteNotebookEntryCommand( + currentUser = currentUser, + notebookEntryId = 15L, + ) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(notebookEntryRepository.findById(15L)).thenReturn(Optional.of(existing)) + + service.deleteNotebookEntry(command) + + Mockito.verify(notebookEntryRepository).delete(existing) + } + + @Test + fun `delete notebook entry rejects other pupils entry`() { + val currentUserResolver = Mockito.mock(CurrentUserResolver::class.java) + val notebookEntryRepository = Mockito.mock(NotebookEntryRepository::class.java) + val mapStopsRepository = Mockito.mock(MapStopsRepository::class.java) + val service = NotebookService(notebookEntryRepository, currentUserResolver, mapStopsRepository) + val currentUser = currentUser("42") + val pupil = pupilUser(42L) + val existing = notebookEntry(15L, pupilUser(99L)) + val command = DeleteNotebookEntryCommand( + currentUser = currentUser, + notebookEntryId = 15L, + ) + + Mockito.`when`(currentUserResolver.requirePupil("42")).thenReturn(pupil) + Mockito.`when`(notebookEntryRepository.findById(15L)).thenReturn(Optional.of(existing)) + + val exception = assertThrows { + service.deleteNotebookEntry(command) + } + + assertEquals(HttpStatus.FORBIDDEN, exception.statusCode) + } + + private fun currentUser(subject: String) = CurrentUser( + subject = subject, + portalType = "pupil", + email = null, + authorities = setOf("ROLE_PUPIL"), + ) + + private fun pupilUser(id: Long) = User( + id = id, + username = "pupil-$id", + passwordHash = "encoded-secret", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE, + ) + + private fun classroom(id: Long) = Classroom( + id = id, + ownerTeacherId = 500L, + title = "Classroom $id", + description = null, + joinCode = "JOIN$id", + ) + + private fun stop(id: Long) = MapStop( + id = id, + slug = "stop-$id", + title = "Stop $id", + ) + + private fun notebookEntry(id: Long, pupil: User) = NotebookEntry( + id = id, + pupil = pupil, + classroom = classroom(7L), + stop = stop(9L), + sourceType = NotebookSourceType.PUPIL, + title = "Entry $id", + content = "Content $id", + ) +} From 3f385b41d0902ff44fd2d463779665065478e4a0 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:21:08 +0200 Subject: [PATCH 08/13] Add migration schema Signed-off-by: sindrelm --- .../V15__create_notebook_entries_table.sql | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/main/resources/db/migration/V15__create_notebook_entries_table.sql diff --git a/src/main/resources/db/migration/V15__create_notebook_entries_table.sql b/src/main/resources/db/migration/V15__create_notebook_entries_table.sql new file mode 100644 index 00000000..18f8cc99 --- /dev/null +++ b/src/main/resources/db/migration/V15__create_notebook_entries_table.sql @@ -0,0 +1,23 @@ +CREATE TABLE notebook_entries ( + id BIGINT NOT NULL AUTO_INCREMENT, + pupil_user_id BIGINT NOT NULL, + classroom_id BIGINT NOT NULL, + stop_id BIGINT NOT NULL, + source_type ENUM('GAME', 'PUPIL') NOT NULL, + title VARCHAR(255) NOT NULL, + content TEXT NOT NULL, + 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_notebook_entries PRIMARY KEY (id), + CONSTRAINT fk_notebook_entries_pupil + FOREIGN KEY (pupil_user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_notebook_entries_classroom + FOREIGN KEY (classroom_id) REFERENCES classrooms (id) ON DELETE CASCADE, + CONSTRAINT fk_notebook_entries_stop + FOREIGN KEY (stop_id) REFERENCES map_stops (id) ON DELETE CASCADE +); + +CREATE INDEX idx_notebook_entries_pupil ON notebook_entries (pupil_user_id); +CREATE INDEX idx_notebook_entries_classroom ON notebook_entries (classroom_id); +CREATE INDEX idx_notebook_entries_stop ON notebook_entries (stop_id); +CREATE INDEX idx_notebook_entries_pupil_classroom ON notebook_entries (pupil_user_id, classroom_id); From 89c6aba11dc50cf3e856b803503cfeca9a68d1fe Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:21:37 +0200 Subject: [PATCH 09/13] Add notebook bootstrap data Signed-off-by: sindrelm --- .../backend/bootstrap/DevDataBootstrap.kt | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt index 97186f9e..6cde1f78 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/bootstrap/DevDataBootstrap.kt @@ -28,6 +28,9 @@ import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import edu.ntnu.idi.idatt.backend.iam.domain.UserStatus import edu.ntnu.idi.idatt.backend.iam.infrastructure.RefreshTokenRepository import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository +import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookEntry +import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookSourceType +import edu.ntnu.idi.idatt.backend.notebook.infrastructure.NotebookEntryRepository import edu.ntnu.idi.idatt.backend.users.avatar.domain.UserAvatar import edu.ntnu.idi.idatt.backend.users.avatar.infrastructure.UserAvatarRepository import edu.ntnu.idi.idatt.backend.users.profile.domain.PupilProfile @@ -64,6 +67,7 @@ class DevDataBootstrap( private val userAvatarRepository: UserAvatarRepository, private val refreshTokenRepository: RefreshTokenRepository, private val pupilGameProgressRepository: PupilGameProgressRepository, + private val notebookEntryRepository: NotebookEntryRepository, private val passwordEncoder: PasswordEncoder, private val mapStopBootstrap: MapStopBootstrap, private val mapStopsRepository: MapStopsRepository, @@ -157,6 +161,12 @@ class DevDataBootstrap( teacher = teacher, stops = mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc(), ) + seedNotebookEntries( + classroom = sampleClassroom, + pupilAda = pupilAda, + pupilNoah = pupilNoah, + stops = mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc(), + ) pupilProgressSeedingService.seedIfAbsent( pupil = pupilAda, @@ -366,6 +376,78 @@ class DevDataBootstrap( MessageDigest.getInstance("SHA-256").digest(rawToken.toByteArray(StandardCharsets.UTF_8)), ) + private fun seedNotebookEntries( + classroom: Classroom, + pupilAda: User, + pupilNoah: User, + stops: List, + ) { + val activeStopsBySlug = stops.associateBy { requireNotNull(it.slug) { "Seeded map stop must have a slug" } } + + activeStopsBySlug["nyhetskvartalet"]?.let { stop -> + seedNotebookEntry( + pupil = pupilAda, + classroom = classroom, + stop = stop, + sourceType = NotebookSourceType.PUPIL, + title = "Merkelige overskrifter", + 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, + classroom = classroom, + stop = stop, + sourceType = NotebookSourceType.PUPIL, + title = "Bildesøk hjalp", + content = "Noah fant samme bilde i en eldre artikkel og skrev ned at kontekst manglet i innlegget.", + ) + } + } + + private fun seedNotebookEntry( + 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 + } + if (existingEntry != null) { + existingEntry.sourceType = sourceType + existingEntry.content = content + return + } + + notebookEntryRepository.save( + NotebookEntry( + pupil = pupil, + classroom = classroom, + stop = stop, + sourceType = sourceType, + title = title, + content = content, + ), + ) + } + private fun seedTasks( classroom: Classroom, teacher: User, From 790dfa6ebf452315a40e7e73f04803740f6e4e30 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:22:00 +0200 Subject: [PATCH 10/13] Remove lob Signed-off-by: sindrelm --- .../edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt index f1b597b6..544379a3 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookEntry.kt @@ -12,7 +12,6 @@ import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn -import jakarta.persistence.Lob import jakarta.persistence.ManyToOne import jakarta.persistence.Table import org.hibernate.annotations.CreationTimestamp @@ -52,7 +51,6 @@ class NotebookEntry( var sourceType: NotebookSourceType, @Column(name = "title", nullable = false) var title: String, - @Lob @Column(name = "content", nullable = false) var content: String, @CreationTimestamp From 251868a2b63c1940c6209def7aaaa0ecaea0c961 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:34:58 +0200 Subject: [PATCH 11/13] Add missing Kdocs Signed-off-by: sindrelm --- .../notebook/api/NotebookEntryApiMappings.kt | 12 +++++++ .../notebook/api/NotebookEntryController.kt | 17 ++++++++++ .../notebook/api/NotebookEntryRequests.kt | 9 +++++ .../notebook/api/NotebookEntryResponses.kt | 10 ++++++ .../notebook/application/NotebookService.kt | 34 +++++++++++++++++-- .../notebook/domain/NotebookSourceType.kt | 12 ++++++- 6 files changed, 90 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt index 1f99fb66..d3ffd859 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryApiMappings.kt @@ -8,6 +8,8 @@ import edu.ntnu.idi.idatt.backend.notebook.domain.NotebookEntry /** * Converts a notebook entry entity into the public API response payload. + * + * @return serialized notebook entry response */ fun NotebookEntry.toResponse(): NotebookEntryResponse = NotebookEntryResponse( @@ -24,6 +26,9 @@ fun NotebookEntry.toResponse(): NotebookEntryResponse = /** * Converts the create request payload into an application command. + * + * @param currentUser authenticated principal for the request + * @return create command consumed by the service layer */ fun CreateNotebookEntryRequest.toCommand(currentUser: CurrentUser): CreateNotebookEntryCommand = CreateNotebookEntryCommand( @@ -37,6 +42,10 @@ fun CreateNotebookEntryRequest.toCommand(currentUser: CurrentUser): CreateNotebo /** * Converts the update request payload into an application command. + * + * @param currentUser authenticated principal for the request + * @param notebookEntryId notebook entry id from the request path + * @return update command consumed by the service layer */ fun UpdateNotebookEntryRequest.toCommand( currentUser: CurrentUser, @@ -51,6 +60,9 @@ fun UpdateNotebookEntryRequest.toCommand( /** * Converts the authenticated principal and path id into a delete command. + * + * @param notebookEntryId notebook entry id from the request path + * @return delete command consumed by the service layer */ fun CurrentUser.toDeleteCommand(notebookEntryId: Long): DeleteNotebookEntryCommand = DeleteNotebookEntryCommand( diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt index d1946bc5..e92c99ed 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryController.kt @@ -17,6 +17,8 @@ import org.springframework.web.bind.annotation.RestController /** * REST API for the authenticated pupil's notebook entries. + * + * @property notebookService application service that handles notebook entry operations */ @RestController @RequestMapping("/api/v1/users/me/notebook-entries") @@ -25,6 +27,9 @@ class NotebookEntryController( ) { /** * Returns all notebook entries owned by the authenticated pupil. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @return notebook entries serialized for the API layer */ @GetMapping fun getNotebookEntries( @@ -34,6 +39,10 @@ class NotebookEntryController( /** * Creates a new notebook entry for the authenticated pupil. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @param request notebook entry payload to persist + * @return created notebook entry */ @PostMapping @ResponseStatus(HttpStatus.CREATED) @@ -45,6 +54,11 @@ class NotebookEntryController( /** * Updates one notebook entry owned by the authenticated pupil. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @param notebookEntryId notebook entry id from the request path + * @param request notebook entry payload to persist + * @return updated notebook entry */ @PutMapping("/{notebookEntryId}") fun updateNotebookEntry( @@ -56,6 +70,9 @@ class NotebookEntryController( /** * Deletes one notebook entry owned by the authenticated pupil. + * + * @param currentUser authenticated principal resolved from the JWT access token + * @param notebookEntryId notebook entry id from the request path */ @DeleteMapping("/{notebookEntryId}") @ResponseStatus(HttpStatus.NO_CONTENT) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt index 780e58fc..b078a540 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt @@ -7,6 +7,12 @@ import jakarta.validation.constraints.NotNull /** * Request payload for creating a notebook entry. + * + * @property classroomId classroom the entry belongs to + * @property stopId map stop the entry belongs to + * @property sourceType origin of the entry content + * @property title short notebook entry title + * @property content full notebook entry body */ data class CreateNotebookEntryRequest( @field:Min(1) @@ -23,6 +29,9 @@ data class CreateNotebookEntryRequest( /** * Request payload for updating a notebook entry. + * + * @property title updated notebook entry title + * @property content updated notebook entry body */ data class UpdateNotebookEntryRequest( @field:NotBlank diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt index d1bfc3b3..216bc290 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryResponses.kt @@ -4,6 +4,16 @@ import java.time.Instant /** * Serialized notebook entry returned by notebook endpoints. + * + * @property id notebook entry identifier + * @property pupilUserId owner pupil user id + * @property classroomId classroom id for the entry context + * @property stopId map stop id for the entry context + * @property sourceType serialized notebook source type + * @property title notebook entry title + * @property content notebook entry body + * @property createdAt timestamp when the entry was created + * @property updatedAt timestamp when the entry was last updated */ data class NotebookEntryResponse( val id: Long, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt index 676e888c..28990854 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt @@ -10,13 +10,25 @@ import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import org.springframework.web.server.ResponseStatusException +/** + * Application service responsible for notebook entry access control and persistence. + * + * @property notebookEntryRepository repository used to load and persist notebook entries + * @property currentUserResolver resolver used to enforce that only pupil users access notebook entries + * @property mapStopsRepository repository used to validate referenced map stops during creation + */ @Service class NotebookService( private val notebookEntryRepository: NotebookEntryRepository, private val currentUserResolver: CurrentUserResolver, private val mapStopsRepository: MapStopsRepository, ) { - + /** + * Returns all notebook entries owned by the authenticated pupil. + * + * @param currentUser authenticated principal resolved from the access token + * @return notebook entries owned by the pupil + */ @Transactional(readOnly = true) fun getAllNotebookEntries(currentUser: CurrentUser): List { val pupil = currentUserResolver.requirePupil(currentUser.subject) @@ -24,6 +36,12 @@ class NotebookService( return notebookEntryRepository.findAllByPupilId(pupilId) } + /** + * Creates one notebook entry for the authenticated pupil in the active classroom context. + * + * @param command application-layer create payload + * @return persisted notebook entry + */ @Transactional fun createNotebookEntry(command: CreateNotebookEntryCommand): NotebookEntry { val pupil = currentUserResolver.requirePupil(command.currentUser.subject) @@ -49,6 +67,12 @@ class NotebookService( return notebookEntryRepository.save(notebookEntry) } + /** + * Updates one existing notebook entry owned by the authenticated pupil. + * + * @param command application-layer update payload + * @return updated notebook entry + */ @Transactional fun updateNotebookEntry(command: UpdateNotebookEntryCommand): NotebookEntry { val pupil = currentUserResolver.requirePupil(command.currentUser.subject) @@ -69,6 +93,11 @@ class NotebookService( return notebookEntryRepository.save(notebookEntry) } + /** + * Deletes one existing notebook entry owned by the authenticated pupil. + * + * @param command application-layer delete payload + */ @Transactional fun deleteNotebookEntry(command: DeleteNotebookEntryCommand) { val pupil = currentUserResolver.requirePupil(command.currentUser.subject) @@ -83,7 +112,6 @@ class NotebookService( throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot delete another pupil's notebook entry") } - notebookEntryRepository.delete(notebookEntry) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookSourceType.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookSourceType.kt index 07611e69..ba9d00f8 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookSourceType.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/domain/NotebookSourceType.kt @@ -1,6 +1,16 @@ package edu.ntnu.idi.idatt.backend.notebook.domain +/** + * Origin of the notebook entry contents. + */ enum class NotebookSourceType { + /** + * Entry content was generated from the game flow. + */ GAME, + + /** + * Entry content was written directly by the pupil. + */ PUPIL, -} \ No newline at end of file +} From 3cd0a86767c14de3078864ab6a00a8b761f992f6 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:36:00 +0200 Subject: [PATCH 12/13] Change sourceType to var Signed-off-by: sindrelm --- .../idi/idatt/backend/notebook/api/NotebookEntryRequests.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt index b078a540..7fcdb662 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/api/NotebookEntryRequests.kt @@ -20,7 +20,7 @@ data class CreateNotebookEntryRequest( @field:Min(1) val stopId: Long, @field:NotNull - val sourceType: NotebookSourceType, + var sourceType: NotebookSourceType, @field:NotBlank val title: String, @field:NotBlank From 2099ec268c1e36b85251ad6727fefea7d2040f12 Mon Sep 17 00:00:00 2001 From: sindrelm Date: Wed, 22 Apr 2026 11:44:01 +0200 Subject: [PATCH 13/13] Refactor logic into a verifyOwnership helper method Signed-off-by: sindrelm --- .../notebook/application/NotebookService.kt | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt index 28990854..2317c94d 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/notebook/application/NotebookService.kt @@ -76,16 +76,7 @@ class NotebookService( @Transactional fun updateNotebookEntry(command: UpdateNotebookEntryCommand): NotebookEntry { val pupil = currentUserResolver.requirePupil(command.currentUser.subject) - val pupilId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" } - - val notebookEntry = notebookEntryRepository.findById(command.notebookEntryId).orElseThrow { - ResponseStatusException(HttpStatus.NOT_FOUND, "Notebook entry not found") - } - - val ownerId = requireNotNull(notebookEntry.pupil.id) { "Notebook entry pupil is missing an id" } - if (ownerId != pupilId) { - throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot update another pupil's notebook entry") - } + val notebookEntry = verifyOwnership(pupil.id, command.notebookEntryId) notebookEntry.title = command.title notebookEntry.content = command.content @@ -101,17 +92,29 @@ class NotebookService( @Transactional fun deleteNotebookEntry(command: DeleteNotebookEntryCommand) { val pupil = currentUserResolver.requirePupil(command.currentUser.subject) - val pupilId = requireNotNull(pupil.id) { "Authenticated pupil is missing an id" } + val notebookEntry = verifyOwnership(pupil.id, command.notebookEntryId) + notebookEntryRepository.delete(notebookEntry) + } - val notebookEntry = notebookEntryRepository.findById(command.notebookEntryId).orElseThrow { + /** + * Loads one notebook entry and verifies that it is owned by the supplied pupil. + * + * @param pupilId authenticated pupil user id + * @param entryId notebook entry id to validate + * @return notebook entry after ownership has been verified + */ + private fun verifyOwnership(pupilId: Long?, entryId: Long): NotebookEntry { + val resolvedPupilId = requireNotNull(pupilId) { "Authenticated pupil is missing an id" } + + val notebookEntry = notebookEntryRepository.findById(entryId).orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "Notebook entry not found") } val ownerId = requireNotNull(notebookEntry.pupil.id) { "Notebook entry pupil is missing an id" } - if (ownerId != pupilId) { - throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot delete another pupil's notebook entry") + if (ownerId != resolvedPupilId) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Pupil cannot access another pupil's notebook entry") } - notebookEntryRepository.delete(notebookEntry) + return notebookEntry } }