From 4ab8487d1be994d383660813b1fa2de9cdc4855d Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Fri, 17 Apr 2026 14:36:19 +0200 Subject: [PATCH 01/26] !start adding necessary stuff for classroom management --- .../classroom/api/ClassroomApiMappings.kt | 57 +++++++++++++ .../classroom/api/ClassroomController.kt | 42 ++++++++++ .../classroom/api/ClassroomDetailResponse.kt | 10 +++ .../classroom/api/ClassroomMemberResponse.kt | 9 +++ .../classroom/api/ClassroomPupilResponse.kt | 8 ++ .../classroom/api/ClassroomResponse.kt | 9 +++ .../classroom/api/ClassroomTeacherResponse.kt | 7 ++ .../classroom/api/CreateClassroomRequest.kt | 12 +++ .../idatt/backend/classroom/api/PupilDto.kt | 8 ++ .../classroom/api/UpdateClassroomRequest.kt | 12 +++ .../classroom/application/ClassroomService.kt | 81 ++++++++++++++++++- .../application/CreateClassroomCommand.kt | 7 ++ .../application/UpdateClassroomCommand.kt | 8 ++ .../backend/classroom/domain/Classroom.kt | 59 +++++++++++++- .../domain/ClassroomPupilMembership.kt | 4 + .../domain/ClassroomTeacherMembership.kt | 32 ++++++++ .../infrastructure/ClassroomRepository.kt | 2 + .../V8_create_classroom_teachers_table.sql | 8 ++ 18 files changed, 373 insertions(+), 2 deletions(-) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt create mode 100644 src/main/resources/db/migration/V8_create_classroom_teachers_table.sql diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt index bac2973c..3d820e64 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt @@ -1,7 +1,10 @@ package edu.ntnu.idi.idatt.backend.classroom.api +import edu.ntnu.idi.idatt.backend.classroom.application.CreateClassroomCommand import edu.ntnu.idi.idatt.backend.classroom.application.JoinClassroomCommand import edu.ntnu.idi.idatt.backend.classroom.application.JoinClassroomResult +import edu.ntnu.idi.idatt.backend.classroom.application.UpdateClassroomCommand +import edu.ntnu.idi.idatt.backend.classroom.domain.* fun JoinClassroomRequest.toCommand(authenticatedSubject: String): JoinClassroomCommand = JoinClassroomCommand( @@ -16,3 +19,57 @@ fun JoinClassroomResult.toJoinClassroomResponse(): JoinClassroomResponse = membershipStatus = membershipStatus, message = message, ) + +fun CreateClassroomRequest.toCommand(subject: String) = + CreateClassroomCommand( + title = name, + description = description, + authenticatedSubject = subject, + ) + +fun UpdateClassroomRequest.toCommand(id: Long) = + UpdateClassroomCommand( + classroomId = id, + title = name, + description = description, + teacherUserIds = teacherUserIds, + ) + +fun Classroom.toResponse(): ClassroomResponse = + ClassroomResponse( + id = id, + name = title, + description = description, + joinCode = joinCode ?: "", + teacherUserIds = teacherUserIds.toList(), //AHHHHH + ) + +fun Classroom.toDetailResponse(): ClassroomDetailResponse = + ClassroomDetailResponse( + id = id, + name = title, + description = description, + joinCode = joinCode ?: "", + + teachers = teacherMemberships.map { + ClassroomTeacherResponse( + userId = it.teacher!!.id!!, + displayName = it.teacher!!.username ?: "Unknown", + email = it.teacher!!.email, + ) + }, + + pupils = pupilMemberships + .sortedWith( + compareByDescending { it.pupil?.xp ?: 0 } + .thenByDescending { it.pupil?.level ?: 0 } + ) + .map { + ClassroomPupilResponse( + userId = it.pupil!!.id!!, + displayName = it.pupil!!.username ?: "Unknown", + xp = it.pupil!!.xp ?: 0, + level = it.pupil!!.level ?: 1, + ) + } + ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index f31924e4..2bf03c48 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -1,6 +1,7 @@ package edu.ntnu.idi.idatt.backend.classroom.api import edu.ntnu.idi.idatt.backend.classroom.application.ClassroomService +import edu.ntnu.idi.idatt.backend.classroom.application.CreateClassroomCommand import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import jakarta.validation.Valid import org.springframework.security.core.annotation.AuthenticationPrincipal @@ -8,6 +9,7 @@ import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController +import org.springframework.web.bind.annotation.* /** * HTTP endpoints for classroom actions. @@ -18,6 +20,15 @@ class ClassroomController( private val classroomService: ClassroomService, ) { + @PostMapping + fun createClassroom( + @RequestBody @Valid request: CreateClassroomRequest, + @AuthenticationPrincipal currentUser: CurrentUser, + ): ClassroomResponse = + classroomService.createClassroom( + request.toCommand(currentUser.subject) + ).toResponse() + /** * Endpoint for joining a classroom. * @@ -31,4 +42,35 @@ class ClassroomController( @AuthenticationPrincipal currentUser: CurrentUser, ): JoinClassroomResponse = classroomService.joinClassroom(request.toCommand(currentUser.subject)).toJoinClassroomResponse() + + @GetMapping("/{id}") + fun getClassroomById( + @PathVariable id: Long + ): ClassroomDetailResponse = + classroomService.getClassroomById(id).toDetailResponse() + + @PutMapping("/{id}") + fun updateClassroom( + @PathVariable id: Long, + @RequestBody @Valid request: UpdateClassroomRequest, + @AuthenticationPrincipal currentUser: CurrentUser, + ): ClassroomResponse = + classroomService.updateClassroom( + request.toCommand(id) + ).toResponse() + + @DeleteMapping("/{classroomId}/pupils/{pupilId}") + fun removePupil( + @PathVariable classroomId: Long, + @PathVariable pupilId: Long, + ) { + classroomService.removePupil(classroomId, pupilId) + } + + @PostMapping("/{classroomId}/pupils/{pupilId}/approve") + fun approvePupil( + @PathVariable classroomId: Long, + @PathVariable pupilId: Long, + ) { + classroomService.approvePupil(classroomId, pupilId)} } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt new file mode 100644 index 00000000..1e4262da --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt @@ -0,0 +1,10 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +data class ClassroomDetailResponse( + val id: Long, + val name: String, + val description: String?, + val joinCode: String, + val teacherUserIds: List, + val pupils: List +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt new file mode 100644 index 00000000..f12ba5c8 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt @@ -0,0 +1,9 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +data class ClassroomMemberResponse( + val userId: Long, + val displayName: String, + val email: String, + val totalXp: Int, + val currentLevel: Int, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt new file mode 100644 index 00000000..32ed2667 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt @@ -0,0 +1,8 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +data class ClassroomPupilResponse ( + val userId: Long, + val displayName: String, + val xp: Int, + val level: Int, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt new file mode 100644 index 00000000..230ecdf7 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt @@ -0,0 +1,9 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +data class ClassroomResponse ( + val id: Long, + val name: String, + val description: String?, + val joinCode: String, + val teacherUserIds: List, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt new file mode 100644 index 00000000..98b74a04 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt @@ -0,0 +1,7 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +data class ClassroomTeacherResponse ( + val userId: Long, + val displayName: String, + val email: String?, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt new file mode 100644 index 00000000..13ac2e9a --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt @@ -0,0 +1,12 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +import jakarta.validation.constraints.NotBlank +import jakarta.validation.constraints.Size + +data class CreateClassroomRequest( + @field:NotBlank + @field:Size(max = 100) + val name: String, + + val description: String? = null, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt new file mode 100644 index 00000000..a113f864 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt @@ -0,0 +1,8 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +data class PupilDto( + val userId: Long, + val displayName: String, + val xp: Int, + val level: Int, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt new file mode 100644 index 00000000..e50f771a --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt @@ -0,0 +1,12 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +import jakarta.validation.constraints.NotBlank + +data class UpdateClassroomRequest ( + @field:NotBlank + val name: String, + + val description: String? = null, + + val teacherUserIds: List = emptyList(), + ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index 51d5ef17..395c093d 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -1,8 +1,11 @@ package edu.ntnu.idi.idatt.backend.classroom.application +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomPupilStatus import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import org.springframework.data.repository.findByIdOrNull import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -20,6 +23,25 @@ class ClassroomService( private val classroomRepository: ClassroomRepository, private val currentUserResolver: CurrentUserResolver, ) { + + @Transactional + fun createClassroom(command: CreateClassroomCommand): Classroom { + val teacher = currentUserResolver.requireTeacherOrAdmin(command.authenticatedSubject) + val joinCode = generateJoinCode() + + val classroom = Classroom( + ownerTeacherId = teacher.id!!, + title = command.title, + description = command.description, + joinCode = joinCode, + status = ClassroomStatus.ACTIVE, + ) + + classroom.addTeacher(teacher) + + return classroomRepository.save(classroom) + } + /** * Adds an authenticated pupil to a classroom as a pending member. * @@ -35,6 +57,7 @@ class ClassroomService( val classroom = classroomRepository.findByJoinCode(normalizedClassroomCode) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + if (classroom.status == ClassroomStatus.INACTIVE) { throw ResponseStatusException(HttpStatus.CONFLICT, "Cannot join an inactive classroom") } @@ -49,11 +72,64 @@ class ClassroomService( return JoinClassroomResult( classroomId = classroom.id, classroomTitle = classroom.title, - membershipStatus = "PENDING", + membershipStatus = ClassroomPupilStatus.PENDING.name, message = "Join request submitted", ) } + @Transactional + fun approvePupil(classroomId: Long, pupilUserId: Long) { + val classroom = classroomRepository.findByIdOrNull(classroomId) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + + classroom.approvePupil(pupilUserId) + classroomRepository.save(classroom) + } + + @Transactional + fun removePupil(classroomId: Long, pupilUserId: Long) { + val classroom = classroomRepository.findByIdOrNull(classroomId) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + + classroom.removePupil(pupilUserId) + classroomRepository.save(classroom) + } + + @Transactional + fun updateClassroom(command: UpdateClassroomCommand): Classroom { + val classroom = classroomRepository.findByIdOrNull(command.classroomId) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + + classroom.title = command.title + classroom.description = command.description + + classroom.teacherMemberships.clear() + + command.teacherUserIds.forEach { teacherId -> + val teacher = currentUserResolver.requireTeacherOrAdmin(teacherId) + classroom.addTeacher(teacher) + } + + return classroomRepository.save(classroom) + } + + @Transactional(readOnly = true) + fun getClassroomById(classroomId: Long): Classroom = + classroomRepository.findByIdOrNull(classroomId) + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + + @Transactional(readOnly = true) + fun getClassrooms(): List = + classroomRepository.findAll() + + @Transactional + fun deleteClassroom(classroomId: Long) { + if (!classroomRepository.existsById(classroomId)) { + throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + } + classroomRepository.deleteById(classroomId) + } + private fun normalizeClassroomCode(classroomCode: String): String { val normalizedCode = classroomCode.trim().uppercase(Locale.ROOT) if (normalizedCode.isBlank()) { @@ -61,4 +137,7 @@ class ClassroomService( } return normalizedCode } + + private fun generateJoinCode(): String = + UUID.randomUUID().toString().take(8).uppercase() } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt new file mode 100644 index 00000000..9c7d49d5 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt @@ -0,0 +1,7 @@ +package edu.ntnu.idi.idatt.backend.classroom.application + +data class CreateClassroomCommand( + val title: String, + val description: String?, + val authenticatedSubject: String, +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt new file mode 100644 index 00000000..4829fdcf --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt @@ -0,0 +1,8 @@ +package edu.ntnu.idi.idatt.backend.classroom.application + +data class UpdateClassroomCommand ( + val classroomId: Long, + val title: String, + val description: String?, + val teacherUserIds: List +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt index 5d4fdec1..36a755ac 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt @@ -40,7 +40,7 @@ class Classroom( var title: String, @Column(name = "description") var description: String? = null, - @Column(name = "join_code", length = 20, unique = true) + @Column(name = "join_code", length = 20, unique = true, nullable = false) var joinCode: String? = null, @Column(name = "status", nullable = false) @Enumerated(EnumType.STRING) @@ -52,6 +52,13 @@ class Classroom( @Column(name = "updated_at", nullable = false) var updatedAt: Instant? = null, + @OneToMany( + mappedBy = "classroom", + cascade = [CascadeType.ALL], + orphanRemoval = true + ) + var teacherMemberships: MutableSet = mutableSetOf(), + @OneToMany( mappedBy = "classroom", cascade = [CascadeType.ALL], @@ -82,4 +89,54 @@ class Classroom( ), ) } + + fun activate() { + status = ClassroomStatus.ACTIVE + } + + fun deactivate() { + status = ClassroomStatus.INACTIVE + } + + fun getMembership(pupilUserId: Long): ClassroomPupilMembership? = + pupilMemberships.find { it.id.pupilUserId == pupilUserId } + + fun approvePupil(pupilUserId: Long) { + val membership = getMembership(pupilUserId) + ?: throw IllegalArgumentException("No membership found") + + membership.status = ClassroomPupilStatus.ACTIVE + membership.approvedAt = Instant.now() + } + + fun removePupil(pupilUserId: Long) { + val removed = pupilMemberships.removeIf { + it.id.pupilUserId == pupilUserId + } + + if (!removed) { + throw IllegalArgumentException("Pupil $pupilUserId is not a member of this classroom") + } + } + + fun addTeacher(teacher: User) { + val userId = requireNotNull(teacher.id) + + teacherMemberships.add( + ClassroomTeacherMembership( + id = ClassroomTeacherMembershipId( + classroomId = id, + teacherUserId = userId, + ), + classroom = this, + teacher = teacher, + ) + ) + } + + fun removeTeacher(teacherUserId: Long) { + teacherMemberships.removeIf { + it.id.teacherUserId == teacherUserId + } + } } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt index 9e7c6bf3..44ea9670 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt @@ -35,4 +35,8 @@ class ClassroomPupilMembership( var joinedAt: Instant = Instant.now(), @Column(name = "approved_at") var approvedAt: Instant? = null, + @Column(name = "xp", nullable = false) + var xp: Int = 0, + @Column(name = "level", nullable = false) + var level: Int = 1, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt new file mode 100644 index 00000000..74bedd4b --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt @@ -0,0 +1,32 @@ +package edu.ntnu.idi.idatt.backend.classroom.domain + +import edu.ntnu.idi.idatt.backend.iam.domain.User +import jakarta.persistence.EmbeddedId +import jakarta.persistence.Table +import jakarta.persistence.Entity +import jakarta.persistence.MapsId +import jakarta.persistence.* +import java.io.* + +@Entity +@Table(name = "classroom_teachers") +class ClassroomTeacherMembership( + @EmbeddedId + var id: ClassroomTeacherMembershipId = ClassroomTeacherMembershipId(), + + @ManyToOne(fetch = FetchType.LAZY) + @MapsId("classromId") + @JoinColumn(name = "classroom_id") + var classroom: Classroom? = null, + + @ManyToOne(fetch = FetchType.LAZY) + @MapsId("teacherUserId") + @JoinColumn(name = "teacher_user_id") + var teacher: User? = null, +) + +@Embeddable +data class ClassroomTeacherMembershipId( + var classroomId: Long = 0, + var teacherUserId: Long = 0, +) : Serializable \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt index 3c54ee2b..2ef1a972 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt @@ -13,4 +13,6 @@ interface ClassroomRepository : JpaRepository { * @return The classroom if found, or null otherwise. */ fun findByJoinCode(code: String): Classroom? + + fun findByIdOrNull(classroomId: String): Classroom? } \ No newline at end of file diff --git a/src/main/resources/db/migration/V8_create_classroom_teachers_table.sql b/src/main/resources/db/migration/V8_create_classroom_teachers_table.sql new file mode 100644 index 00000000..a1e11ccc --- /dev/null +++ b/src/main/resources/db/migration/V8_create_classroom_teachers_table.sql @@ -0,0 +1,8 @@ +CREATE TABLE classroom_teachers ( + classroom_id BIGINT NOT NULL, + teacher_user_id BIGINT NOT NULL, + + PRIMARY KEY (classroom_id, teacher_user_id), + CONSTRAINT fk_classroom_teacher_classroom FOREIGN KEY (classroom_id) REFERENCES classrooms(id) ON DELETE CASCADE, + CONSTRAINT fk_classroom_teacher_user FOREIGN KEY (teacher_user_id) REFERENCES user(id) ON DELETE CASCADE +); \ No newline at end of file From 5f6624501b3f805dbad7d3fb75550c31e8d87939 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Fri, 17 Apr 2026 15:07:07 +0200 Subject: [PATCH 02/26] add xp and level to user --- src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt index 266d711f..7167bc4f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt @@ -51,6 +51,10 @@ class User( @UpdateTimestamp @Column(name = "updated_at", nullable = false) var updatedAt: Instant? = null, + @Column(name = "xp") + var xp: Int = 0, + @Column(name = "level") + var level: Int = 0, ) { /** * Indicates whether the user can authenticate. From 78e5cf38d4965c66a70d776fdb5e48344badeb0d Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Fri, 17 Apr 2026 15:07:49 +0200 Subject: [PATCH 03/26] naming --- .../backend/classroom/api/ClassroomDetailResponse.kt | 4 ++-- .../idi/idatt/backend/classroom/api/ClassroomResponse.kt | 2 +- .../backend/classroom/api/CreateClassroomRequest.kt | 2 +- .../backend/classroom/api/UpdateClassroomRequest.kt | 2 +- .../classroom/domain/ClassroomTeacherMembership.kt | 9 ++------- 5 files changed, 7 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt index 1e4262da..4bce3f15 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt @@ -2,9 +2,9 @@ package edu.ntnu.idi.idatt.backend.classroom.api data class ClassroomDetailResponse( val id: Long, - val name: String, + val title: String, val description: String?, val joinCode: String, - val teacherUserIds: List, + val teachers: List, val pupils: List ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt index 230ecdf7..faaddfd1 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt @@ -2,7 +2,7 @@ package edu.ntnu.idi.idatt.backend.classroom.api data class ClassroomResponse ( val id: Long, - val name: String, + val title: String, val description: String?, val joinCode: String, val teacherUserIds: List, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt index 13ac2e9a..3c5013d7 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt @@ -6,7 +6,7 @@ import jakarta.validation.constraints.Size data class CreateClassroomRequest( @field:NotBlank @field:Size(max = 100) - val name: String, + val title: String, val description: String? = null, ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt index e50f771a..9b5d1078 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt @@ -4,7 +4,7 @@ import jakarta.validation.constraints.NotBlank data class UpdateClassroomRequest ( @field:NotBlank - val name: String, + val title: String, val description: String? = null, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt index 74bedd4b..df3d42a1 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt @@ -9,13 +9,13 @@ import jakarta.persistence.* import java.io.* @Entity -@Table(name = "classroom_teachers") +@Table(name = "classroom_teachers", uniqueConstraints = [UniqueConstraint(columnNames = ["classroom_id", "teacher_user_id"])]) class ClassroomTeacherMembership( @EmbeddedId var id: ClassroomTeacherMembershipId = ClassroomTeacherMembershipId(), @ManyToOne(fetch = FetchType.LAZY) - @MapsId("classromId") + @MapsId("classroomId") @JoinColumn(name = "classroom_id") var classroom: Classroom? = null, @@ -25,8 +25,3 @@ class ClassroomTeacherMembership( var teacher: User? = null, ) -@Embeddable -data class ClassroomTeacherMembershipId( - var classroomId: Long = 0, - var teacherUserId: Long = 0, -) : Serializable \ No newline at end of file From ee9216e622dffab8377ee3ff08cf86df6d24289c Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Fri, 17 Apr 2026 15:08:11 +0200 Subject: [PATCH 04/26] move embeddable --- .../domain/ClassroomTeacherMembershipId.kt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt new file mode 100644 index 00000000..7d804daa --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt @@ -0,0 +1,14 @@ +package edu.ntnu.idi.idatt.backend.classroom.domain + +import jakarta.persistence.Column +import jakarta.persistence.Embeddable +import java.io.Serializable + +@Embeddable +data class ClassroomTeacherMembershipId( + @Column(name = "classroom_id") + var classroomId: Long = 0, + @Column(name = "teacher_user_id") + var teacherUserId: Long = 0, +) : Serializable + From 3c87070dbb2aff3db13d6b5dc7d711366e7c7a44 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Fri, 17 Apr 2026 15:08:37 +0200 Subject: [PATCH 05/26] fix --- .../classroom/api/ClassroomApiMappings.kt | 53 ++++++++++--------- .../classroom/api/ClassroomController.kt | 2 +- .../classroom/api/ClassroomTeacherResponse.kt | 1 - .../classroom/application/ClassroomService.kt | 2 +- .../application/UpdateClassroomCommand.kt | 3 +- 5 files changed, 33 insertions(+), 28 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt index 3d820e64..1980b874 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt @@ -12,50 +12,53 @@ fun JoinClassroomRequest.toCommand(authenticatedSubject: String): JoinClassroomC authenticatedSubject = authenticatedSubject, ) -fun JoinClassroomResult.toJoinClassroomResponse(): JoinClassroomResponse = - JoinClassroomResponse( - classroomId = classroomId, - classroomTitle = classroomTitle, - membershipStatus = membershipStatus, - message = message, - ) - -fun CreateClassroomRequest.toCommand(subject: String) = +fun CreateClassroomRequest.toCommand(subject: String): CreateClassroomCommand = CreateClassroomCommand( - title = name, + title = title, description = description, authenticatedSubject = subject, ) -fun UpdateClassroomRequest.toCommand(id: Long) = +fun UpdateClassroomRequest.toCommand(id: Long, authenticatedSubject: String): UpdateClassroomCommand = UpdateClassroomCommand( classroomId = id, - title = name, + title = title, description = description, teacherUserIds = teacherUserIds, + authenticatedSubject = authenticatedSubject, + ) + +fun JoinClassroomResult.toJoinClassroomResponse(): JoinClassroomResponse = + JoinClassroomResponse( + classroomId = classroomId, + classroomTitle = classroomTitle, + membershipStatus = membershipStatus, + message = message, ) + fun Classroom.toResponse(): ClassroomResponse = ClassroomResponse( id = id, - name = title, + title = title, description = description, joinCode = joinCode ?: "", - teacherUserIds = teacherUserIds.toList(), //AHHHHH + teacherUserIds = teacherMemberships.mapNotNull { it.teacher?.id } ) fun Classroom.toDetailResponse(): ClassroomDetailResponse = ClassroomDetailResponse( id = id, - name = title, + title = title, description = description, joinCode = joinCode ?: "", - teachers = teacherMemberships.map { + teachers = teacherMemberships.mapNotNull { membership -> + val teacher = membership.teacher ?: return@mapNotNull null + ClassroomTeacherResponse( - userId = it.teacher!!.id!!, - displayName = it.teacher!!.username ?: "Unknown", - email = it.teacher!!.email, + userId = teacher.id ?: return@mapNotNull null, + email = teacher.email, ) }, @@ -64,12 +67,14 @@ fun Classroom.toDetailResponse(): ClassroomDetailResponse = compareByDescending { it.pupil?.xp ?: 0 } .thenByDescending { it.pupil?.level ?: 0 } ) - .map { + .mapNotNull { membership -> + val pupil = membership.pupil ?: return@mapNotNull null + ClassroomPupilResponse( - userId = it.pupil!!.id!!, - displayName = it.pupil!!.username ?: "Unknown", - xp = it.pupil!!.xp ?: 0, - level = it.pupil!!.level ?: 1, + userId = pupil.id ?: return@mapNotNull null, + displayName = pupil.username ?: "Unknown", + xp = pupil.xp ?: 0, + level = pupil.level ?: 1, ) } ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index 2bf03c48..aac9927e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -56,7 +56,7 @@ class ClassroomController( @AuthenticationPrincipal currentUser: CurrentUser, ): ClassroomResponse = classroomService.updateClassroom( - request.toCommand(id) + request.toCommand(id, currentUser.subject) ).toResponse() @DeleteMapping("/{classroomId}/pupils/{pupilId}") diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt index 98b74a04..fdd965dc 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt @@ -2,6 +2,5 @@ package edu.ntnu.idi.idatt.backend.classroom.api data class ClassroomTeacherResponse ( val userId: Long, - val displayName: String, val email: String?, ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index 395c093d..1ed78fb8 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -106,7 +106,7 @@ class ClassroomService( classroom.teacherMemberships.clear() command.teacherUserIds.forEach { teacherId -> - val teacher = currentUserResolver.requireTeacherOrAdmin(teacherId) + val teacher = currentUserResolver.requireTeacherOrAdmin(command.authenticatedSubject) classroom.addTeacher(teacher) } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt index 4829fdcf..9c2e987d 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt @@ -4,5 +4,6 @@ data class UpdateClassroomCommand ( val classroomId: Long, val title: String, val description: String?, - val teacherUserIds: List + val teacherUserIds: List, + val authenticatedSubject: String, ) \ No newline at end of file From d6bb45b34896b869396e1fcd3951740ae55e8db4 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Fri, 17 Apr 2026 15:09:12 +0200 Subject: [PATCH 06/26] delete unused --- .../idatt/backend/classroom/api/ClassroomController.kt | 1 - .../backend/classroom/api/ClassroomMemberResponse.kt | 9 --------- 2 files changed, 10 deletions(-) delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index aac9927e..7510503e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -1,7 +1,6 @@ package edu.ntnu.idi.idatt.backend.classroom.api import edu.ntnu.idi.idatt.backend.classroom.application.ClassroomService -import edu.ntnu.idi.idatt.backend.classroom.application.CreateClassroomCommand import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import jakarta.validation.Valid import org.springframework.security.core.annotation.AuthenticationPrincipal diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt deleted file mode 100644 index f12ba5c8..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomMemberResponse.kt +++ /dev/null @@ -1,9 +0,0 @@ -package edu.ntnu.idi.idatt.backend.classroom.api - -data class ClassroomMemberResponse( - val userId: Long, - val displayName: String, - val email: String, - val totalXp: Int, - val currentLevel: Int, -) \ No newline at end of file From caaee2720dc7f5f48777ff6fecab13fc817e9b4e Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 00:14:19 +0200 Subject: [PATCH 07/26] fix stuff --- .../classroom/api/ClassroomApiMappings.kt | 2 +- .../classroom/api/ClassroomController.kt | 4 +++ .../classroom/api/UpdateClassroomRequest.kt | 2 +- .../classroom/application/ClassroomService.kt | 31 +++++++++++++++---- .../application/UpdateClassroomCommand.kt | 2 +- .../backend/classroom/domain/Classroom.kt | 1 + .../infrastructure/ClassroomRepository.kt | 2 +- .../iam/infrastructure/UserRepository.kt | 2 ++ .../db/migration/V1__create_users_table.sql | 2 ++ ...> V8__create_classroom_teachers_table.sql} | 2 +- 10 files changed, 39 insertions(+), 11 deletions(-) rename src/main/resources/db/migration/{V8_create_classroom_teachers_table.sql => V8__create_classroom_teachers_table.sql} (88%) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt index 1980b874..cbd48810 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt @@ -24,7 +24,7 @@ fun UpdateClassroomRequest.toCommand(id: Long, authenticatedSubject: String): Up classroomId = id, title = title, description = description, - teacherUserIds = teacherUserIds, + teacherEmails = teacherEmails, authenticatedSubject = authenticatedSubject, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index 7510503e..a797af22 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -28,6 +28,10 @@ class ClassroomController( request.toCommand(currentUser.subject) ).toResponse() + @GetMapping + fun getClassrooms(): List = + classroomService.getClassrooms().map { it.toResponse() } + /** * Endpoint for joining a classroom. * diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt index 9b5d1078..be9be2c9 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt @@ -8,5 +8,5 @@ data class UpdateClassroomRequest ( val description: String? = null, - val teacherUserIds: List = emptyList(), + val teacherEmails: List = emptyList(), ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index 1ed78fb8..b3bbbb1c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -5,6 +5,7 @@ import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomPupilStatus import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver +import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository import org.springframework.data.repository.findByIdOrNull import org.springframework.http.HttpStatus import org.springframework.stereotype.Service @@ -22,6 +23,7 @@ import java.util.* class ClassroomService( private val classroomRepository: ClassroomRepository, private val currentUserResolver: CurrentUserResolver, + private val userRepository: UserRepository, ) { @Transactional @@ -55,20 +57,28 @@ 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") if (classroom.status == ClassroomStatus.INACTIVE) { + println("❌ REJECTED: classroom is INACTIVE") throw ResponseStatusException(HttpStatus.CONFLICT, "Cannot join an inactive classroom") } if (classroom.hasPupilMembership(userId)) { + println("❌ REJECTED: user already a member (userId=$userId)") throw ResponseStatusException(HttpStatus.CONFLICT, "User already a member") } classroom.addPupilMembership(user) classroomRepository.save(classroom) + println("📦 classroom loaded: id=${classroom.id}, status=${classroom.status}") + return JoinClassroomResult( classroomId = classroom.id, classroomTitle = classroom.title, @@ -79,7 +89,7 @@ class ClassroomService( @Transactional fun approvePupil(classroomId: Long, pupilUserId: Long) { - val classroom = classroomRepository.findByIdOrNull(classroomId) + val classroom = classroomRepository.findById(classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") classroom.approvePupil(pupilUserId) @@ -88,7 +98,7 @@ class ClassroomService( @Transactional fun removePupil(classroomId: Long, pupilUserId: Long) { - val classroom = classroomRepository.findByIdOrNull(classroomId) + val classroom = classroomRepository.findById(classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") classroom.removePupil(pupilUserId) @@ -97,16 +107,25 @@ class ClassroomService( @Transactional fun updateClassroom(command: UpdateClassroomCommand): Classroom { - val classroom = classroomRepository.findByIdOrNull(command.classroomId) + val classroom = classroomRepository.findById(command.classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") classroom.title = command.title classroom.description = command.description + val emails = command.teacherEmails.map { it.trim().lowercase(Locale.ROOT) } + + val teachers = userRepository.findAllByEmailIgnoreCaseIn(emails) + + if (teachers.size != emails.size) { + val foundEmails = teachers.mapNotNull { it.email?.lowercase(Locale.ROOT) } + val missing = emails - foundEmails.toSet() + throw ResponseStatusException(HttpStatus.CONFLICT, "Teachers not found: $missing") + } + classroom.teacherMemberships.clear() - command.teacherUserIds.forEach { teacherId -> - val teacher = currentUserResolver.requireTeacherOrAdmin(command.authenticatedSubject) + teachers.forEach { teacher -> classroom.addTeacher(teacher) } @@ -115,7 +134,7 @@ class ClassroomService( @Transactional(readOnly = true) fun getClassroomById(classroomId: Long): Classroom = - classroomRepository.findByIdOrNull(classroomId) + classroomRepository.findById(classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") @Transactional(readOnly = true) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt index 9c2e987d..ccd28a9c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt @@ -4,6 +4,6 @@ data class UpdateClassroomCommand ( val classroomId: Long, val title: String, val description: String?, - val teacherUserIds: List, + val teacherEmails: List, val authenticatedSubject: String, ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt index 36a755ac..5f529aae 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt @@ -120,6 +120,7 @@ class Classroom( } fun addTeacher(teacher: User) { + val userId = requireNotNull(teacher.id) teacherMemberships.add( diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt index 2ef1a972..182ae26f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt @@ -14,5 +14,5 @@ interface ClassroomRepository : JpaRepository { */ fun findByJoinCode(code: String): Classroom? - fun findByIdOrNull(classroomId: String): Classroom? + } \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/UserRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/UserRepository.kt index 2d1bdab8..9a21ede5 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/UserRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/infrastructure/UserRepository.kt @@ -15,6 +15,8 @@ interface UserRepository : JpaRepository { */ fun findByEmailIgnoreCase(email: String): User? + fun findAllByEmailIgnoreCaseIn(emails: List): List + /** * Finds a user by username without case sensitivity. * diff --git a/src/main/resources/db/migration/V1__create_users_table.sql b/src/main/resources/db/migration/V1__create_users_table.sql index 44805059..1981988a 100644 --- a/src/main/resources/db/migration/V1__create_users_table.sql +++ b/src/main/resources/db/migration/V1__create_users_table.sql @@ -7,6 +7,8 @@ CREATE TABLE users ( status ENUM('ACTIVE', 'INACTIVE', 'SUSPENDED') 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), + xp INTEGER, + level INTEGER, CONSTRAINT pk_users PRIMARY KEY (id), CONSTRAINT chk_users_login_identifier CHECK ( (role = 'PUPIL' AND username IS NOT NULL AND email IS NULL) diff --git a/src/main/resources/db/migration/V8_create_classroom_teachers_table.sql b/src/main/resources/db/migration/V8__create_classroom_teachers_table.sql similarity index 88% rename from src/main/resources/db/migration/V8_create_classroom_teachers_table.sql rename to src/main/resources/db/migration/V8__create_classroom_teachers_table.sql index a1e11ccc..c726523d 100644 --- a/src/main/resources/db/migration/V8_create_classroom_teachers_table.sql +++ b/src/main/resources/db/migration/V8__create_classroom_teachers_table.sql @@ -4,5 +4,5 @@ CREATE TABLE classroom_teachers ( PRIMARY KEY (classroom_id, teacher_user_id), CONSTRAINT fk_classroom_teacher_classroom FOREIGN KEY (classroom_id) REFERENCES classrooms(id) ON DELETE CASCADE, - CONSTRAINT fk_classroom_teacher_user FOREIGN KEY (teacher_user_id) REFERENCES user(id) ON DELETE CASCADE + CONSTRAINT fk_classroom_teacher_user FOREIGN KEY (teacher_user_id) REFERENCES users(id) ON DELETE CASCADE ); \ No newline at end of file From ad1c339dbea9cc32397f246422b015fe3dc37027 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 09:02:13 +0200 Subject: [PATCH 08/26] remove unused edits --- .../idatt/backend/classroom/api/ClassroomApiMappings.kt | 6 ------ .../idatt/backend/classroom/api/ClassroomPupilResponse.kt | 2 -- .../backend/classroom/application/ClassroomService.kt | 8 ++++---- .../resources/db/migration/V1__create_users_table.sql | 2 -- 4 files changed, 4 insertions(+), 14 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt index cbd48810..68f1c1dc 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt @@ -63,18 +63,12 @@ fun Classroom.toDetailResponse(): ClassroomDetailResponse = }, pupils = pupilMemberships - .sortedWith( - compareByDescending { it.pupil?.xp ?: 0 } - .thenByDescending { it.pupil?.level ?: 0 } - ) .mapNotNull { membership -> val pupil = membership.pupil ?: return@mapNotNull null ClassroomPupilResponse( userId = pupil.id ?: return@mapNotNull null, displayName = pupil.username ?: "Unknown", - xp = pupil.xp ?: 0, - level = pupil.level ?: 1, ) } ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt index 32ed2667..d32d04c3 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt @@ -3,6 +3,4 @@ package edu.ntnu.idi.idatt.backend.classroom.api data class ClassroomPupilResponse ( val userId: Long, val displayName: String, - val xp: Int, - val level: Int, ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index b3bbbb1c..08a26a99 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -57,7 +57,7 @@ class ClassroomService( val user = currentUserResolver.requirePupil(command.authenticatedSubject) val userId = requireNotNull(user.id) { "Authenticated user is missing an id" } - println("➡️ JOIN CLASSROOM REQUEST") + println("JOIN CLASSROOM REQUEST") println("code = ${command.classroomCode}") println("user = ${command.authenticatedSubject}") @@ -65,19 +65,19 @@ class ClassroomService( ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") if (classroom.status == ClassroomStatus.INACTIVE) { - println("❌ REJECTED: classroom is INACTIVE") + println("REJECTED: classroom is INACTIVE") throw ResponseStatusException(HttpStatus.CONFLICT, "Cannot join an inactive classroom") } if (classroom.hasPupilMembership(userId)) { - println("❌ REJECTED: user already a member (userId=$userId)") + println("REJECTED: user already a member (userId=$userId)") throw ResponseStatusException(HttpStatus.CONFLICT, "User already a member") } classroom.addPupilMembership(user) classroomRepository.save(classroom) - println("📦 classroom loaded: id=${classroom.id}, status=${classroom.status}") + println("Classroom loaded: id=${classroom.id}, status=${classroom.status}") return JoinClassroomResult( classroomId = classroom.id, diff --git a/src/main/resources/db/migration/V1__create_users_table.sql b/src/main/resources/db/migration/V1__create_users_table.sql index 1981988a..44805059 100644 --- a/src/main/resources/db/migration/V1__create_users_table.sql +++ b/src/main/resources/db/migration/V1__create_users_table.sql @@ -7,8 +7,6 @@ CREATE TABLE users ( status ENUM('ACTIVE', 'INACTIVE', 'SUSPENDED') 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), - xp INTEGER, - level INTEGER, CONSTRAINT pk_users PRIMARY KEY (id), CONSTRAINT chk_users_login_identifier CHECK ( (role = 'PUPIL' AND username IS NOT NULL AND email IS NULL) From 2f0d45905c508e3ec11e9464bc19afa62113445d Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 09:49:05 +0200 Subject: [PATCH 09/26] spacing --- .../classroom/api/ClassroomApiMappings.kt | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt index 68f1c1dc..553809df 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt @@ -36,7 +36,6 @@ fun JoinClassroomResult.toJoinClassroomResponse(): JoinClassroomResponse = message = message, ) - fun Classroom.toResponse(): ClassroomResponse = ClassroomResponse( id = id, @@ -62,13 +61,12 @@ fun Classroom.toDetailResponse(): ClassroomDetailResponse = ) }, - pupils = pupilMemberships - .mapNotNull { membership -> - val pupil = membership.pupil ?: return@mapNotNull null + pupils = pupilMemberships.mapNotNull { membership -> + val pupil = membership.pupil ?: return@mapNotNull null - ClassroomPupilResponse( - userId = pupil.id ?: return@mapNotNull null, - displayName = pupil.username ?: "Unknown", - ) - } + ClassroomPupilResponse( + userId = pupil.id ?: return@mapNotNull null, + displayName = pupil.username ?: "Unknown", + ) + } ) \ No newline at end of file From 19fac020c2a3ecb84df40969cb69d4a6992d3565 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 09:49:13 +0200 Subject: [PATCH 10/26] remove unused --- .../backend/classroom/domain/ClassroomPupilMembership.kt | 4 ---- src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt | 4 ---- 2 files changed, 8 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt index 44ea9670..9e7c6bf3 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomPupilMembership.kt @@ -35,8 +35,4 @@ class ClassroomPupilMembership( var joinedAt: Instant = Instant.now(), @Column(name = "approved_at") var approvedAt: Instant? = null, - @Column(name = "xp", nullable = false) - var xp: Int = 0, - @Column(name = "level", nullable = false) - var level: Int = 1, ) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt index 7167bc4f..266d711f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/domain/User.kt @@ -51,10 +51,6 @@ class User( @UpdateTimestamp @Column(name = "updated_at", nullable = false) var updatedAt: Instant? = null, - @Column(name = "xp") - var xp: Int = 0, - @Column(name = "level") - var level: Int = 0, ) { /** * Indicates whether the user can authenticate. From a5cb3e8fb1c3e2d5da9edb8e1bd1cbb40c513383 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 09:49:19 +0200 Subject: [PATCH 11/26] kdocs --- .../classroom/api/ClassroomController.kt | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index a797af22..eb0b1387 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -19,6 +19,13 @@ class ClassroomController( private val classroomService: ClassroomService, ) { + /** + * Endpoint for creating a classroom. + * + * @param request The create classroom request containing the classroom information. + * @param currentUser The authenticated user attempting to create the classroom. + * @return the created classroom. + */ @PostMapping fun createClassroom( @RequestBody @Valid request: CreateClassroomRequest, @@ -28,6 +35,11 @@ class ClassroomController( request.toCommand(currentUser.subject) ).toResponse() + /** + * Retrieves all classrooms available to authenticated user. + * + * @return a list of classrooms. + */ @GetMapping fun getClassrooms(): List = classroomService.getClassrooms().map { it.toResponse() } @@ -46,12 +58,25 @@ class ClassroomController( ): JoinClassroomResponse = classroomService.joinClassroom(request.toCommand(currentUser.subject)).toJoinClassroomResponse() + /** + * Retrieves information about a specific classroom. + * + * @param id the unique id of the classroom. + * @return classroom details. + */ @GetMapping("/{id}") fun getClassroomById( @PathVariable id: Long ): ClassroomDetailResponse = classroomService.getClassroomById(id).toDetailResponse() + /** + * Endpoint for updating classroom information. + * + * @param id the unique id of the classroom to be updated. + * @param request the update classroom request containing the updated classroom data. + * @param currentUser the updated classroom. + */ @PutMapping("/{id}") fun updateClassroom( @PathVariable id: Long, @@ -62,6 +87,12 @@ class ClassroomController( request.toCommand(id, currentUser.subject) ).toResponse() + /** + * Endpoint for removing a pupil from a classroom. + * + * @param classroomId the id of the classroom the pupil should be removed from. + * @param pupilId the id of the student being removed. + */ @DeleteMapping("/{classroomId}/pupils/{pupilId}") fun removePupil( @PathVariable classroomId: Long, @@ -70,6 +101,12 @@ class ClassroomController( classroomService.removePupil(classroomId, pupilId) } + /** + * Approves a pupils request to join a classroom. + * + * @param classroomId the id of the classroom the pupil is requesting to join. + * @param pupilId the id of the pupil requesting to join. + */ @PostMapping("/{classroomId}/pupils/{pupilId}/approve") fun approvePupil( @PathVariable classroomId: Long, From e0b6edc53986afddfcbc1c8ec12b966f3760c54e Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 10:47:00 +0200 Subject: [PATCH 12/26] kdocs --- .../classroom/api/ClassroomApiMappings.kt | 9 ++- .../classroom/api/ClassroomController.kt | 10 ++- .../classroom/api/ClassroomDetailResponse.kt | 10 +++ .../classroom/api/ClassroomPupilResponse.kt | 8 ++- .../classroom/api/ClassroomResponse.kt | 11 ++- .../classroom/api/ClassroomTeacherResponse.kt | 8 ++- .../classroom/api/CreateClassroomRequest.kt | 6 ++ .../idatt/backend/classroom/api/PupilDto.kt | 8 --- .../classroom/api/UpdateClassroomRequest.kt | 11 ++- .../classroom/application/ClassroomService.kt | 67 +++++++++++++++++-- .../application/CreateClassroomCommand.kt | 9 +++ .../application/UpdateClassroomCommand.kt | 13 +++- .../backend/classroom/domain/Classroom.kt | 49 +++++++++++--- .../domain/ClassroomTeacherMembership.kt | 2 - .../domain/ClassroomTeacherMembershipId.kt | 5 ++ .../infrastructure/ClassroomRepository.kt | 2 - 16 files changed, 185 insertions(+), 43 deletions(-) delete mode 100644 src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt index 553809df..2e9db967 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt @@ -4,7 +4,7 @@ import edu.ntnu.idi.idatt.backend.classroom.application.CreateClassroomCommand import edu.ntnu.idi.idatt.backend.classroom.application.JoinClassroomCommand import edu.ntnu.idi.idatt.backend.classroom.application.JoinClassroomResult import edu.ntnu.idi.idatt.backend.classroom.application.UpdateClassroomCommand -import edu.ntnu.idi.idatt.backend.classroom.domain.* +import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom fun JoinClassroomRequest.toCommand(authenticatedSubject: String): JoinClassroomCommand = JoinClassroomCommand( @@ -19,7 +19,10 @@ fun CreateClassroomRequest.toCommand(subject: String): CreateClassroomCommand = authenticatedSubject = subject, ) -fun UpdateClassroomRequest.toCommand(id: Long, authenticatedSubject: String): UpdateClassroomCommand = +fun UpdateClassroomRequest.toCommand( + id: Long, + authenticatedSubject: String +): UpdateClassroomCommand = UpdateClassroomCommand( classroomId = id, title = title, @@ -61,7 +64,7 @@ fun Classroom.toDetailResponse(): ClassroomDetailResponse = ) }, - pupils = pupilMemberships.mapNotNull { membership -> + pupils = pupilMemberships.mapNotNull { membership -> val pupil = membership.pupil ?: return@mapNotNull null ClassroomPupilResponse( diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index eb0b1387..19933269 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -4,10 +4,6 @@ import edu.ntnu.idi.idatt.backend.classroom.application.ClassroomService import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser import jakarta.validation.Valid import org.springframework.security.core.annotation.AuthenticationPrincipal -import org.springframework.web.bind.annotation.PostMapping -import org.springframework.web.bind.annotation.RequestBody -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RestController import org.springframework.web.bind.annotation.* /** @@ -56,7 +52,8 @@ class ClassroomController( @RequestBody @Valid request: JoinClassroomRequest, @AuthenticationPrincipal currentUser: CurrentUser, ): JoinClassroomResponse = - classroomService.joinClassroom(request.toCommand(currentUser.subject)).toJoinClassroomResponse() + classroomService.joinClassroom(request.toCommand(currentUser.subject)) + .toJoinClassroomResponse() /** * Retrieves information about a specific classroom. @@ -112,5 +109,6 @@ class ClassroomController( @PathVariable classroomId: Long, @PathVariable pupilId: Long, ) { - classroomService.approvePupil(classroomId, pupilId)} + classroomService.approvePupil(classroomId, pupilId) + } } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt index 4bce3f15..34e2236f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt @@ -1,5 +1,15 @@ package edu.ntnu.idi.idatt.backend.classroom.api +/** + * DTO for response to retrieving classroom details. + * + * @param id the id of the classroom. + * @param title the title of the classroom. + * @param description the description of the classroom. + * @param joinCode the code for joining the classroom. + * @param teachers a list of the teachers that are members of the classroom. + * @param pupils a list of the pupils that are members of the classroom. + */ data class ClassroomDetailResponse( val id: Long, val title: String, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt index d32d04c3..bf32893e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt @@ -1,6 +1,12 @@ package edu.ntnu.idi.idatt.backend.classroom.api -data class ClassroomPupilResponse ( +/** + * DTO for response to retrieving pupil information for a classroom. + * + * @param userId the id of a pupil in the classroom. + * @param displayName the name of a pupil in the classroom. + */ +data class ClassroomPupilResponse( val userId: Long, val displayName: String, ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt index faaddfd1..6cd92255 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt @@ -1,6 +1,15 @@ package edu.ntnu.idi.idatt.backend.classroom.api -data class ClassroomResponse ( +/** + * DTO for response to classroom requests. + * + * @param id the id of a classroom. + * @param title the title of a classroom. + * @param description the optional description of a classroom. + * @param joinCode the code to join the classroom. + * @param teacherUserIds a list of ids of teahcers belonging to the classroom. + */ +data class ClassroomResponse( val id: Long, val title: String, val description: String?, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt index fdd965dc..4a5ca51d 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt @@ -1,6 +1,12 @@ package edu.ntnu.idi.idatt.backend.classroom.api -data class ClassroomTeacherResponse ( +/** + * DTO for response to retrieving teacher information for a classroom. + * + * @param userId the id of a teacher in the classroom. + * @param email the email address of a teacher in the classroom. + */ +data class ClassroomTeacherResponse( val userId: Long, val email: String?, ) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt index 3c5013d7..5512335f 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt @@ -3,6 +3,12 @@ package edu.ntnu.idi.idatt.backend.classroom.api import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.Size +/** + * DTO for request to create a classroom. + * + * @property title the title of the classroom to be created. Must not be blank. + * @property description the optional description of the classroom. + */ data class CreateClassroomRequest( @field:NotBlank @field:Size(max = 100) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt deleted file mode 100644 index a113f864..00000000 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/PupilDto.kt +++ /dev/null @@ -1,8 +0,0 @@ -package edu.ntnu.idi.idatt.backend.classroom.api - -data class PupilDto( - val userId: Long, - val displayName: String, - val xp: Int, - val level: Int, -) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt index be9be2c9..87299f8c 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt @@ -2,11 +2,18 @@ package edu.ntnu.idi.idatt.backend.classroom.api import jakarta.validation.constraints.NotBlank -data class UpdateClassroomRequest ( +/** + * DTO for requests to update classroom information. + * + * @property title the title of the classroom. Must not be blank. + * @property description the description of the classroom. + * @property teacherEmails a list of emails of teachers belonging to the classroom. + */ +data class UpdateClassroomRequest( @field:NotBlank val title: String, val description: String? = null, val teacherEmails: List = emptyList(), - ) \ No newline at end of file +) \ No newline at end of file diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index 08a26a99..ba010ac0 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -6,7 +6,6 @@ import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository -import org.springframework.data.repository.findByIdOrNull import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -18,6 +17,7 @@ import java.util.* * * @property classroomRepository repository for classroom access * @property currentUserResolver shared resolver for the authenticated user and role guard + * @property userRepository: userRepository repository for user access */ @Service class ClassroomService( @@ -26,6 +26,13 @@ class ClassroomService( private val userRepository: UserRepository, ) { + /** + * Creates a new classroom owned by the authenticated teacher. + * A unique code is generated for the classroom, and the creating user is automatically added as a teacher member. + * + * @param command contains classroom details and authenticated user subject. + * @return the newly created classroom entity. + */ @Transactional fun createClassroom(command: CreateClassroomCommand): Classroom { val teacher = currentUserResolver.requireTeacherOrAdmin(command.authenticatedSubject) @@ -65,20 +72,16 @@ class ClassroomService( ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") if (classroom.status == ClassroomStatus.INACTIVE) { - println("REJECTED: classroom is INACTIVE") throw ResponseStatusException(HttpStatus.CONFLICT, "Cannot join an inactive classroom") } if (classroom.hasPupilMembership(userId)) { - println("REJECTED: user already a member (userId=$userId)") throw ResponseStatusException(HttpStatus.CONFLICT, "User already a member") } classroom.addPupilMembership(user) classroomRepository.save(classroom) - println("Classroom loaded: id=${classroom.id}, status=${classroom.status}") - return JoinClassroomResult( classroomId = classroom.id, classroomTitle = classroom.title, @@ -87,6 +90,13 @@ class ClassroomService( ) } + /** + * Approves a pending pupil membership in a classroom. + * + * @param classroomId the id of the classroom. + * @param pupilUserId the id of the pupil to approve. + * @throws ResponseStatusException if the classroom does not exist. + */ @Transactional fun approvePupil(classroomId: Long, pupilUserId: Long) { val classroom = classroomRepository.findById(classroomId).orElse(null) @@ -96,6 +106,13 @@ class ClassroomService( classroomRepository.save(classroom) } + /** + * Removes a pupil from a classroom. + * + * @param classroomId the id of the classroom. + * @param pupilUserId the id of the pupil to remove. + * @throws ResponseStatusException if the classroom does not exist. + */ @Transactional fun removePupil(classroomId: Long, pupilUserId: Long) { val classroom = classroomRepository.findById(classroomId).orElse(null) @@ -105,10 +122,18 @@ class ClassroomService( classroomRepository.save(classroom) } + /** + * Updates classroom metadata and assigned teachers. + * Existing teacher memberships are replaced with the provided list. All teacher emails must correspond to existing users. + * + * @param command contains updated classroom data and teacher emails. + * @return the updated classroom entity. + * @throws ResponseStatusException if the classroom does not exist or if one or more teacher emails cannot be resolved. + */ @Transactional fun updateClassroom(command: UpdateClassroomCommand): Classroom { val classroom = classroomRepository.findById(command.classroomId).orElse(null) - ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") classroom.title = command.title classroom.description = command.description @@ -132,15 +157,33 @@ class ClassroomService( return classroomRepository.save(classroom) } + /** + * Retrieves a classroom by its id. + * + * @param classroomId the id of the classroom. + * @return the matching classroom. + * @throws ResponseStatusException if the classroom does not exist. + */ @Transactional(readOnly = true) fun getClassroomById(classroomId: Long): Classroom = classroomRepository.findById(classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + /** + * Retrieves all classrooms. + * + * @return a list of all classroom entities. + */ @Transactional(readOnly = true) fun getClassrooms(): List = classroomRepository.findAll() + /** + * Deletes a classsroom by its id. + * + * @param classroomId the id of the classroom to remove. + * @throws ResponseStatusException if the classroom does not exist. + */ @Transactional fun deleteClassroom(classroomId: Long) { if (!classroomRepository.existsById(classroomId)) { @@ -149,6 +192,13 @@ class ClassroomService( classroomRepository.deleteById(classroomId) } + /** + * Normalizes a classroom join code by trimming whitespace and converting to uppercase. + * + * @param classroomCode the raw classroom code. + * @return the normalized classroom code. + * @throws ResponseStatusException if the code is blank. + */ private fun normalizeClassroomCode(classroomCode: String): String { val normalizedCode = classroomCode.trim().uppercase(Locale.ROOT) if (normalizedCode.isBlank()) { @@ -157,6 +207,11 @@ class ClassroomService( return normalizedCode } + /** + * Generates a random uppercase join code for a classroom. + * + * @return a random 8-character join code. + */ private fun generateJoinCode(): String = UUID.randomUUID().toString().take(8).uppercase() } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt index 9c7d49d5..d5b1b9d8 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt @@ -1,5 +1,14 @@ package edu.ntnu.idi.idatt.backend.classroom.application +/** + * Command representing the intent to create a classroom. + * + * This is part of the application layer and should not depend on HTTP or framework-specific classes. + * + * @property title the title of the classroom. + * @property description the optional description of the classroom. + * @property authenticatedSubject JWT subject for the authenticated subject user attempting to create the classroom. + */ data class CreateClassroomCommand( val title: String, val description: String?, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt index ccd28a9c..ae2639eb 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt @@ -1,6 +1,17 @@ package edu.ntnu.idi.idatt.backend.classroom.application -data class UpdateClassroomCommand ( +/** + * Command representing the intent to update a classrooms metadata. + * + * This is part of the application layer and should not depend on HTTP or framework-specific classes. + * + * @property classroomId the id of the classroom being updated. + * @property title the updated title of the classroom. + * @property description the updated description of the classroom. + * @property teacherEmails the updated list of emails of teachers members of the classroom. + * @property authenticatedSubject JWT subject for the authenticated subject user attempting to update the classroom. + */ +data class UpdateClassroomCommand( val classroomId: Long, val title: String, val description: String?, diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt index 5f529aae..b7d3854b 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/Classroom.kt @@ -1,16 +1,7 @@ package edu.ntnu.idi.idatt.backend.classroom.domain import edu.ntnu.idi.idatt.backend.iam.domain.User -import jakarta.persistence.CascadeType -import jakarta.persistence.Column -import jakarta.persistence.Entity -import jakarta.persistence.EnumType -import jakarta.persistence.Enumerated -import jakarta.persistence.GeneratedValue -import jakarta.persistence.GenerationType -import jakarta.persistence.Id -import jakarta.persistence.OneToMany -import jakarta.persistence.Table +import jakarta.persistence.* import org.hibernate.annotations.CreationTimestamp import org.hibernate.annotations.UpdateTimestamp import java.time.Instant @@ -26,6 +17,7 @@ import java.time.Instant * @property status Current status of the classroom (e.g., ACTIVE or INACTIVE). * @property createdAt Timestamp when the classroom was created. * @property updatedAt Timestamp for the last update of the classroom. + * @property teacherMemberships Teacher membership rows for this classroom. * @property pupilMemberships Pupil membership rows for this classroom. */ @Entity @@ -90,17 +82,37 @@ class Classroom( ) } + /** + * Marks the classroom as active. + */ fun activate() { status = ClassroomStatus.ACTIVE } + /** + * Marks the classroom as inactive. + */ fun deactivate() { status = ClassroomStatus.INACTIVE } + /** + * Retrieves a pupil membership by user id. + * + * @param pupilUserId the id of the pupil. + * @return the matching membership, or null if not found. + */ fun getMembership(pupilUserId: Long): ClassroomPupilMembership? = pupilMemberships.find { it.id.pupilUserId == pupilUserId } + /** + * Approves a pending pupil membership. + * + * The pupils membership status is set as active and the approval timestamp is set. + * + * @param pupilUserId the id of the pupil to approve. + * @throws IllegalArgumentException if no membership exists for the pupil. + */ fun approvePupil(pupilUserId: Long) { val membership = getMembership(pupilUserId) ?: throw IllegalArgumentException("No membership found") @@ -109,6 +121,12 @@ class Classroom( membership.approvedAt = Instant.now() } + /** + * Removes a pupil from the classroom. + * + * @param pupilUserId the id of the pupil to remove. + * @throws IllegalArgumentException if the pupil is not a member of the classroom. + */ fun removePupil(pupilUserId: Long) { val removed = pupilMemberships.removeIf { it.id.pupilUserId == pupilUserId @@ -119,6 +137,12 @@ class Classroom( } } + /** + * Adds a teacher to the classroom. + * + * @param teacher the user to add as a teacher. + * @throws IllegalArgumentException if the teacher has no id. + */ fun addTeacher(teacher: User) { val userId = requireNotNull(teacher.id) @@ -135,6 +159,11 @@ class Classroom( ) } + /** + * Removes a teacher from the classroom. + * + * @param teacherUserId the id of the teacher to remove. + */ fun removeTeacher(teacherUserId: Long) { teacherMemberships.removeIf { it.id.teacherUserId == teacherUserId diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt index df3d42a1..8b2ce918 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt @@ -13,12 +13,10 @@ import java.io.* class ClassroomTeacherMembership( @EmbeddedId var id: ClassroomTeacherMembershipId = ClassroomTeacherMembershipId(), - @ManyToOne(fetch = FetchType.LAZY) @MapsId("classroomId") @JoinColumn(name = "classroom_id") var classroom: Classroom? = null, - @ManyToOne(fetch = FetchType.LAZY) @MapsId("teacherUserId") @JoinColumn(name = "teacher_user_id") diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt index 7d804daa..d02c3e45 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt @@ -4,6 +4,11 @@ import jakarta.persistence.Column import jakarta.persistence.Embeddable import java.io.Serializable +/** + * Composite identifier for a classroom membership row. + * + * Uses value equality so JPA can reliably track entity identity in persistence context collections. + */ @Embeddable data class ClassroomTeacherMembershipId( @Column(name = "classroom_id") diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt index 182ae26f..3c54ee2b 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt @@ -13,6 +13,4 @@ interface ClassroomRepository : JpaRepository { * @return The classroom if found, or null otherwise. */ fun findByJoinCode(code: String): Classroom? - - } \ No newline at end of file From 6a8603db3bed676d8db3f9e22288ea6383fd4c54 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 13:28:06 +0200 Subject: [PATCH 13/26] spelling --- .../idi/idatt/backend/classroom/application/ClassroomService.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index ba010ac0..023058d8 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -179,7 +179,7 @@ class ClassroomService( classroomRepository.findAll() /** - * Deletes a classsroom by its id. + * Deletes a classroom by its id. * * @param classroomId the id of the classroom to remove. * @throws ResponseStatusException if the classroom does not exist. From 5a92453dc0b7e6ba90af30e6dd960ca92faa6c85 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 13:28:37 +0200 Subject: [PATCH 14/26] add tests --- .../backend/classroom/ClassroomServiceTest.kt | 232 +++++++++++++++++- 1 file changed, 231 insertions(+), 1 deletion(-) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index 0f885642..4b382427 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -1,7 +1,9 @@ package edu.ntnu.idi.idatt.backend.classroom import edu.ntnu.idi.idatt.backend.classroom.application.ClassroomService +import edu.ntnu.idi.idatt.backend.classroom.application.CreateClassroomCommand import edu.ntnu.idi.idatt.backend.classroom.application.JoinClassroomCommand +import edu.ntnu.idi.idatt.backend.classroom.application.UpdateClassroomCommand import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomPupilMembership import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomPupilMembershipId @@ -12,6 +14,7 @@ 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.infrastructure.UserRepository import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach @@ -22,17 +25,48 @@ import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException +import org.mockito.Mockito.any class ClassroomServiceTest { private lateinit var classroomRepository: ClassroomRepository private lateinit var currentUserResolver: CurrentUserResolver private lateinit var classroomService: ClassroomService + private lateinit var userRepository: UserRepository @BeforeEach fun setup() { classroomRepository = mock(ClassroomRepository::class.java) currentUserResolver = mock(CurrentUserResolver::class.java) - classroomService = ClassroomService(classroomRepository, currentUserResolver) + userRepository = mock(UserRepository::class.java) + classroomService = ClassroomService(classroomRepository, currentUserResolver, userRepository) + } + + @Test + fun `should create classroom and assign teacher`() { + val teacher = User( + id = 1, + email = "teacher@test.com", + username = "teacher", + passwordHash = "pw", + role = UserRole.TEACHER, + status = UserStatus.ACTIVE, + ) + + `when`(currentUserResolver.requireTeacherOrAdmin("1")).thenReturn(teacher) + `when`(classroomRepository.save(any())).thenAnswer { it.arguments[0] } + + val result = classroomService.createClassroom( + CreateClassroomCommand( + title = "Math", + description = "description", + authenticatedSubject = "1" + ) + ) + + assertEquals("Math", result.title) + assertEquals("description", result.description) + assertEquals(1L, result.ownerTeacherId) + assertTrue(result.teacherMemberships.isNotEmpty()) } @Test @@ -184,4 +218,200 @@ class ClassroomServiceTest { verify(classroomRepository).findByJoinCode("ABC123") } + + // approve pupils + @Test + fun `should be able to approve students`() { + val classroom = Classroom(id = 1, ownerTeacherId = 2, title = "class", description = "description", joinCode = "ABC123", status = ClassroomStatus.ACTIVE) + val pupil = User(id = 3, email = null, username = "pupil", passwordHash = "password", role = UserRole.PUPIL, status = UserStatus.ACTIVE) + + classroom.addPupilMembership(pupil) + + `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) + + classroomService.approvePupil(1, 3) + + verify(classroomRepository).findById(1) + verify(classroomRepository).save(classroom) + + val membership = classroom.pupilMemberships.first { it.pupil?.id == 3L } + assertEquals(ClassroomPupilStatus.ACTIVE, membership.status) + } + + @Test + fun `should throw when approving pupil in non-existing classroom`() { + `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.empty()) + + val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { + classroomService.approvePupil(1, 3) + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + verify(classroomRepository, never()).save(any()) + } + + @Test + fun `should remove pupil from classroom`() { + val classroom = Classroom( + id = 1, + ownerTeacherId = 2, + title = "classroom", + description = "description", + joinCode = "ABC123", + status = ClassroomStatus.ACTIVE + ) + + val pupil = User( + id = 3, + email = "pupil@test.com", + username = "pupil", + passwordHash = "password", + role = UserRole.PUPIL, + status = UserStatus.ACTIVE + ) + + classroom.addPupilMembership(pupil) + + `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) + + classroomService.removePupil(1, 3) + + verify(classroomRepository).findById(1) + verify(classroomRepository).save(classroom) + + assertTrue(classroom.pupilMemberships.none { it.pupil?.id == 3L }) + } + + @Test + fun `should throw when removing pupil from non-existing classroom`() { + `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.empty()) + + val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { + classroomService.removePupil(1, 3) + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + verify(classroomRepository, never()).save(any()) + } + + @Test + fun `should update classroom title, description and teachers`() { + val classroom = Classroom( + id = 1, + ownerTeacherId = 2, + title = "old", + description = "old", + joinCode = "ABC123", + status = ClassroomStatus.ACTIVE + ) + + val teacher = User( + id = 10, + email = "teacher@test.com", + username = "teacher", + passwordHash = "password", + role = UserRole.TEACHER, + status = UserStatus.ACTIVE + ) + + `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) + `when`(userRepository.findAllByEmailIgnoreCaseIn(listOf("teacher@test.com"))).thenReturn(listOf(teacher)) + `when`(classroomRepository.save(any())).thenAnswer { it.arguments[0] } + + val command = UpdateClassroomCommand( + classroomId = 1, + title = "new", + description = "new", + teacherEmails = listOf("teacher@test.com"), + authenticatedSubject = "10" + ) + + val result = classroomService.updateClassroom(command) + + assertEquals("new", result.title) + assertEquals("new", result.description) + assertEquals(1, result.teacherMemberships.size) + + verify(classroomRepository).save(classroom) + } + + @Test + fun `should throw when updating classroom with unknown teacher emails`() { + val classroom = Classroom( + id = 1, + ownerTeacherId = 2, + title = "old", + description = "old", + joinCode = "ABC123", + status = ClassroomStatus.ACTIVE + ) + + `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) + `when`(userRepository.findAllByEmailIgnoreCaseIn(listOf("missing@test.com"))).thenReturn(emptyList()) + + val command = UpdateClassroomCommand( + classroomId = 1, + title = "new", + description = "new", + teacherEmails = listOf("missing@test.com"), + authenticatedSubject = "2" + ) + + val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { + classroomService.updateClassroom(command) + } + + assertEquals(HttpStatus.CONFLICT, exception.statusCode) + verify(classroomRepository, never()).save(any()) + } + + @Test + fun `should return all classrooms`() { + val classrooms = listOf( + Classroom( + id = 1, + ownerTeacherId = 2, + title = "classroom 1", + description = "description", + joinCode = "ABC123", + status = ClassroomStatus.ACTIVE + ), + Classroom( + id = 3, + ownerTeacherId = 4, + title = "classroom 2", + description = "description", + joinCode = "123ABC", + status = ClassroomStatus.ACTIVE + ) + ) + + `when`(classroomRepository.findAll()).thenReturn(classrooms) + + val result = classroomService.getClassrooms() + + assertEquals(2, result.size) + verify(classroomRepository).findAll() + } + + @Test + fun `should delete classroom`() { + `when`(classroomRepository.existsById(1)).thenReturn(true) + + classroomService.deleteClassroom(1) + + verify(classroomRepository).deleteById(1) + } + + @Test + fun `should throw when deleteting non-existing classroom`() { + `when`(classroomRepository.existsById(1)).thenReturn(false) + + val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { + classroomService.deleteClassroom(1) + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + verify(classroomRepository, never()).deleteById(any()) + } } From cfe0e34b7f04fea57f46c9596461a2b68ac36959 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 14:08:26 +0200 Subject: [PATCH 15/26] add tests --- .../classroom/ClassroomIntegrationTests.kt | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt index 83ca65eb..13bec0e3 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt @@ -24,7 +24,10 @@ import org.springframework.jdbc.core.JdbcTemplate 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 import java.time.Instant @SpringBootTest @@ -181,6 +184,149 @@ class ClassroomIntegrationTests { } } + @Test + fun `authenticated user can get all classrooms`() { + val classroom = createClassroom("LIST1") + + mockMvc.post("/api/v1/classrooms/join") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer ${pupilAccessToken("listuser", "secret123")}") + content = """{"classroomCode":"LIST1"}""" + } + + mockMvc.get("/api/v1/classrooms") { + header(HttpHeaders.AUTHORIZATION, "Bearer ${pupilAccessToken("listuser", "secret123")}") + }.andExpect { + status { isOk() } + jsonPath("$[0].id") { value(classroom.id.toInt()) } + } + } + + @Test + fun `should get classroom by id`() { + val classroom = createClassroom("DETAIL1") + + val pupil = userRepository.save(activePupil(username = "detailuser")) + val token = pupilAccessToken(username = "detailuser", password = "secret123") + + mockMvc.get("/api/v1/classrooms/${classroom.id}") { + header( + HttpHeaders.AUTHORIZATION, + "Bearer $token" + ) + }.andExpect { + status { isOk() } + jsonPath("$.id") { value(classroom.id.toInt()) } + jsonPath("$.title") { value("Class DETAIL1") } + } + } + + @Test + fun `teacher can create classroom`() { + val teacher = userRepository.save(activeTeacher("teacher-create@test.com")) + val token = teacherPortalAccessToken("teacher-create@test.com", "secret123") + + val request = """ + { + "title": "Test Classroom", + "description": "Test Description" + } + """.trimIndent() + + mockMvc.post("/api/v1/classrooms") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $token") + content = request + }.andExpect { + status { isOk() } + jsonPath("$.title") { value("Test Classroom") } + jsonPath("$.description") { value("Test Description") } + } + } + + @Test + fun `teacher can update classroom`() { + val classroom = createClassroom("UPDATE1") + + val teacher = userRepository.save(activeTeacher("teacher-update@test.com")) + val token = teacherPortalAccessToken("teacher-update@test.com", "secret123") + + val request = """ + { + "title": "Updated Classroom", + "description": "Updated Classroom Description", + "teacherEmails": [] + } + """.trimIndent() + + mockMvc.put("/api/v1/classrooms/${classroom.id}") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $token") + content = request + }.andExpect { + status { isOk() } + jsonPath("$.title") { value("Updated Classroom") } + jsonPath("$.description") { value("Updated Classroom Description") } + } + } + + @Test + fun `teacher can approve pupil`() { + val classroom = createClassroom("APPROVE1") + + val pupil = userRepository.save(activePupil("approveuser")) + val teacherToken = teacherPortalAccessToken("owner-APPROVE1@example.com", "secret123") + + mockMvc.post("/api/v1/classrooms/join") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer ${pupilAccessToken("approveuser", "secret123")}") + content = """{"classroomCode":"APPROVE1"}""" + } + + mockMvc.post("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}/approve") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer $teacherToken") + }.andExpect { + status { isOk() } + } + } + + @Test + fun `teacher can remove pupil from classroom`() { + val classroom = createClassroom("REMOVE1") + + val pupil = userRepository.save(activePupil("removeuser")) + + mockMvc.post("/api/v1/classrooms/join") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer ${pupilAccessToken("removeuser", "secret123")}") + content = """{"classroomCode":"REMOVE1"}""" + } + + val teacherToken = teacherPortalAccessToken("owner-REMOVE1@example.com", "secret123") + + mockMvc.delete("/api/v1/classrooms/${classroom.id}/pupils/${pupil.id}") { + with(csrf()) + header(HttpHeaders.AUTHORIZATION, "Bearer ${teacherToken}") + }.andExpect { + status { isOk() } + } + + val count = jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM classroom_pupils WHERE classroom_id = ? AND pupil_user_id = ?", + Int::class.java, + classroom.id, + pupil.id + ) ?: 0 + + assertEquals(0, count) + } + private fun createClassroom(classroomCode: String): Classroom { val owner = userRepository.save(activeTeacher(email = "owner-$classroomCode@example.com")) return classroomRepository.save( @@ -195,6 +341,7 @@ class ClassroomIntegrationTests { ), ) } + private fun pupilAccessToken(username: String, password: String): String = jsonMapper.readTree( mockMvc.post("/api/v1/auth/pupil/login") { @@ -239,4 +386,6 @@ class ClassroomIntegrationTests { role = UserRole.ADMIN, status = UserStatus.ACTIVE, ) + + } From 01cc9e1f4a009c1d88b195cb21d2facfc15da872 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 14:18:53 +0200 Subject: [PATCH 16/26] rename --- ...eachers_table.sql => V13__create_classroom_teachers_table.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/main/resources/db/migration/{V8__create_classroom_teachers_table.sql => V13__create_classroom_teachers_table.sql} (100%) diff --git a/src/main/resources/db/migration/V8__create_classroom_teachers_table.sql b/src/main/resources/db/migration/V13__create_classroom_teachers_table.sql similarity index 100% rename from src/main/resources/db/migration/V8__create_classroom_teachers_table.sql rename to src/main/resources/db/migration/V13__create_classroom_teachers_table.sql From b4cc4ad1c1d5848e3b4a8925bdd171e490fc0693 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 14:24:27 +0200 Subject: [PATCH 17/26] update test --- .../ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index ba38dbab..43c618e8 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -44,14 +44,13 @@ class ClassroomServiceTest { classroomRepository = mock(ClassroomRepository::class.java) currentUserResolver = mock(CurrentUserResolver::class.java) userRepository = mock(UserRepository::class.java) - classroomService = ClassroomService(classroomRepository, currentUserResolver, userRepository) pupilGameProgressRepository = mock(PupilGameProgressRepository::class.java) eventPublisher = mock(ApplicationEventPublisher::class.java) classroomService = ClassroomService( classroomRepository, currentUserResolver, - pupilGameProgressRepository, userRepository, + pupilGameProgressRepository, eventPublisher, ) } From 881cd1de1a711e842fd6913d979fee68e4666110 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 16:08:51 +0200 Subject: [PATCH 18/26] kdocs --- .../classroom/domain/ClassroomTeacherMembership.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt index 8b2ce918..2b0e5390 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembership.kt @@ -6,8 +6,15 @@ import jakarta.persistence.Table import jakarta.persistence.Entity import jakarta.persistence.MapsId import jakarta.persistence.* -import java.io.* +/** + * Represents the association between a classroom and a teacher. + * A teacher cannot be added multiple times to the same classroom. + * + * @property id Composite identifier containing classroom id and teacher user id. + * @property classroom The classroom this membership belongs to. + * @property teacher The teacher assigned to the classroom. + */ @Entity @Table(name = "classroom_teachers", uniqueConstraints = [UniqueConstraint(columnNames = ["classroom_id", "teacher_user_id"])]) class ClassroomTeacherMembership( From be53343181f6b4942c5f95c16c1444f55fd802bf Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Mon, 20 Apr 2026 17:46:05 +0200 Subject: [PATCH 19/26] add user resolver for teachers --- .../iam/application/ClassroomUserResolver.kt | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt index 780f0c87..fff8ca52 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt @@ -39,6 +39,35 @@ class ClassroomUserResolver( return classroom } + /** + * Verifies that [user] is a teacher in the current classroom. + * + * @param user the authenticated user to check. + * @param classroomId the classroom to verify teacher membership of. + * @return the classroom if [user] is a teacher member. + * @throws ResponseStatusException 404 if the classroom does not exist. + * @throws ResponseStatusException 403 if [user] is not a teacher in the classroom. + */ + fun requireClassroomTeacherAccess(user: User, classroomId: Long): Classroom { + val classroom = classroomRepository.findById(classroomId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + } + + val userId = requireNotNull(user.id) + + val isOwner = classroom.ownerTeacherId == userId + val isTeacherMember = classroom.teacherMemberships.any { + it.id.teacherUserId == userId + } + + if (!isOwner && !isTeacherMember) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Teacher access required") + } + + return classroom + } + /** * Verifies that [user] is a member of the given classroom. * @@ -51,6 +80,7 @@ class ClassroomUserResolver( * @throws ResponseStatusException 403 if [user] is not a member of the classroom */ fun requireClassroomMember(user: User, classroomId: Long): Classroom { + TODO("Not implemented: requires classroom membership table") } } \ No newline at end of file From 8683918a1b958fe54dec757770a0fe14eed7f71a Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Tue, 21 Apr 2026 12:06:13 +0200 Subject: [PATCH 20/26] kdocs --- .../classroom/api/ClassroomApiMappings.kt | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt index 2e9db967..feb77a06 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomApiMappings.kt @@ -6,12 +6,22 @@ import edu.ntnu.idi.idatt.backend.classroom.application.JoinClassroomResult import edu.ntnu.idi.idatt.backend.classroom.application.UpdateClassroomCommand import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom +/** + * Converts the join classroom request to the application command. + * + * @return a command used to process a classroom joining request. + */ fun JoinClassroomRequest.toCommand(authenticatedSubject: String): JoinClassroomCommand = JoinClassroomCommand( classroomCode = classroomCode, authenticatedSubject = authenticatedSubject, ) +/** + * Converts a create classroom request to the application command. + * + * @return a command used to process the creation request. + */ fun CreateClassroomRequest.toCommand(subject: String): CreateClassroomCommand = CreateClassroomCommand( title = title, @@ -19,6 +29,11 @@ fun CreateClassroomRequest.toCommand(subject: String): CreateClassroomCommand = authenticatedSubject = subject, ) +/** + * Converts an update classroom request to the application command. + * + * @return a command used to process the update request. + */ fun UpdateClassroomRequest.toCommand( id: Long, authenticatedSubject: String @@ -31,6 +46,11 @@ fun UpdateClassroomRequest.toCommand( authenticatedSubject = authenticatedSubject, ) +/** + * Maps a join classroom result to a response. + * + * @return a response containing classroom join request details. + */ fun JoinClassroomResult.toJoinClassroomResponse(): JoinClassroomResponse = JoinClassroomResponse( classroomId = classroomId, @@ -39,6 +59,11 @@ fun JoinClassroomResult.toJoinClassroomResponse(): JoinClassroomResponse = message = message, ) +/** + * Maps a classroom domain entity to a classroom response. + * + * @return a classroom response DTO. + */ fun Classroom.toResponse(): ClassroomResponse = ClassroomResponse( id = id, @@ -48,6 +73,11 @@ fun Classroom.toResponse(): ClassroomResponse = teacherUserIds = teacherMemberships.mapNotNull { it.teacher?.id } ) +/** + * Maps a classroom domain entity to a classroom detail response. + * + * @return a detailed classroom response DTO. + */ fun Classroom.toDetailResponse(): ClassroomDetailResponse = ClassroomDetailResponse( id = id, From 6c2fab549fe78f6748e830fd65c74b9c16e37fc8 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Tue, 21 Apr 2026 14:46:50 +0200 Subject: [PATCH 21/26] update authorization needs for classrooms --- .../classroom/api/ClassroomController.kt | 39 +++-- .../classroom/application/ClassroomService.kt | 77 +++++++--- .../infrastructure/ClassroomRepository.kt | 18 +++ .../iam/application/ClassroomUserResolver.kt | 20 +++ .../classroom/ClassroomIntegrationTests.kt | 20 ++- .../backend/classroom/ClassroomServiceTest.kt | 140 +++++++----------- 6 files changed, 196 insertions(+), 118 deletions(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index 19933269..ec219cbd 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -32,13 +32,14 @@ class ClassroomController( ).toResponse() /** - * Retrieves all classrooms available to authenticated user. + * Retrieves all classrooms the authenticated user is a member of. * - * @return a list of classrooms. + * @param currentUser the authenticated user extracted from the security context. + * @return a list of classrooms accessible to the user. */ @GetMapping - fun getClassrooms(): List = - classroomService.getClassrooms().map { it.toResponse() } + fun getClassrooms(@AuthenticationPrincipal currentUser: CurrentUser): List = + classroomService.getClassrooms(currentUser.subject).map { it.toResponse() } /** * Endpoint for joining a classroom. @@ -59,13 +60,15 @@ class ClassroomController( * Retrieves information about a specific classroom. * * @param id the unique id of the classroom. + * @param currentUser the authenticated user extracted form the security context. * @return classroom details. */ @GetMapping("/{id}") fun getClassroomById( - @PathVariable id: Long + @PathVariable id: Long, + @AuthenticationPrincipal currentUser: CurrentUser, ): ClassroomDetailResponse = - classroomService.getClassroomById(id).toDetailResponse() + classroomService.getClassroomById(id, currentUser.subject).toDetailResponse() /** * Endpoint for updating classroom information. @@ -85,17 +88,19 @@ class ClassroomController( ).toResponse() /** - * Endpoint for removing a pupil from a classroom. + * Removes a pupil from a classroom. * * @param classroomId the id of the classroom the pupil should be removed from. * @param pupilId the id of the student being removed. + * @param currentUser the authenticates user extracted from the security context. */ @DeleteMapping("/{classroomId}/pupils/{pupilId}") fun removePupil( @PathVariable classroomId: Long, @PathVariable pupilId: Long, + @AuthenticationPrincipal currentUser: CurrentUser, ) { - classroomService.removePupil(classroomId, pupilId) + classroomService.removePupil(classroomId, pupilId, currentUser.subject) } /** @@ -103,12 +108,28 @@ class ClassroomController( * * @param classroomId the id of the classroom the pupil is requesting to join. * @param pupilId the id of the pupil requesting to join. + * @param currentUser the authenticated user extracted from the security context. */ @PostMapping("/{classroomId}/pupils/{pupilId}/approve") fun approvePupil( @PathVariable classroomId: Long, @PathVariable pupilId: Long, + @AuthenticationPrincipal currentUser: CurrentUser, + ) { + classroomService.approvePupil(classroomId, pupilId, currentUser.subject) + } + + /** + * Deletes a classroom. + * + * @param id the id of the classroom being deleted. + * @param currentUser the authenticated user extracted from the security context. + */ + @DeleteMapping("/{id}") + fun deleteClassroom( + @PathVariable id: Long, + @AuthenticationPrincipal currentUser: CurrentUser, ) { - classroomService.approvePupil(classroomId, pupilId) + classroomService.deleteClassroom(id, currentUser.subject) } } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index b40ba7a6..dd90564b 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -7,6 +7,7 @@ import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgressId import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository +import edu.ntnu.idi.idatt.backend.iam.application.ClassroomUserResolver import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository import org.springframework.context.ApplicationEventPublisher @@ -19,15 +20,19 @@ import java.util.* /** * Application service for classroom membership actions. * - * @property classroomRepository repository for classroom access - * @property currentUserResolver shared resolver for the authenticated user and role guard - * @property userRepository: userRepository repository for user access + * @property classroomRepository repository for classroom access. + * @property currentUserResolver shared resolver for the authenticated user and role guard. + * @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. */ @Service class ClassroomService( private val classroomRepository: ClassroomRepository, private val currentUserResolver: CurrentUserResolver, private val userRepository: UserRepository, + private val classroomUserResolver: ClassroomUserResolver, private val pupilGameProgressRepository: PupilGameProgressRepository, private val eventPublisher: ApplicationEventPublisher, ) { @@ -112,14 +117,23 @@ class ClassroomService( * * @param classroomId the id of the classroom. * @param pupilUserId the id of the pupil to approve. - * @throws ResponseStatusException if the classroom does not exist. + * @param authenticatedSubject JWT subject containing the persisted user id. + * @throws ResponseStatusException if the user is not a teacher in the classroom, if the classroom does not exist or if the pupil is not in the classroom. */ @Transactional - fun approvePupil(classroomId: Long, pupilUserId: Long) { + fun approvePupil(classroomId: Long, pupilUserId: Long, authenticatedSubject: String) { + val currentUser = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + classroomUserResolver.requireClassroomTeacherAccess(currentUser, classroomId) + val classroom = classroomRepository.findById(classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") - classroom.approvePupil(pupilUserId) + try { + classroom.approvePupil(pupilUserId) + } catch (e: IllegalArgumentException) { + throw ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil not found in classroom") + } + classroomRepository.save(classroom) } @@ -128,14 +142,23 @@ class ClassroomService( * * @param classroomId the id of the classroom. * @param pupilUserId the id of the pupil to remove. - * @throws ResponseStatusException if the classroom does not exist. + * @param authenticatedSubject JWT subject containing the persisted user id. + * @throws ResponseStatusException if the user does not own the classroom or the classroom does not exist. */ @Transactional - fun removePupil(classroomId: Long, pupilUserId: Long) { + fun removePupil(classroomId: Long, pupilUserId: Long, authenticatedSubject: String) { + val currentUser = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + classroomUserResolver.requireClassroomOwner(currentUser, classroomId) + val classroom = classroomRepository.findById(classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") - classroom.removePupil(pupilUserId) + try { + classroom.removePupil(pupilUserId) + } catch (e: IllegalArgumentException) { + throw ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil not found in classroom") + } + classroomRepository.save(classroom) } @@ -145,10 +168,13 @@ class ClassroomService( * * @param command contains updated classroom data and teacher emails. * @return the updated classroom entity. - * @throws ResponseStatusException if the classroom does not exist or if one or more teacher emails cannot be resolved. + * @throws ResponseStatusException if the user does not own the classroom, if the classroom does not exist or if one or more teacher emails cannot be resolved. */ @Transactional fun updateClassroom(command: UpdateClassroomCommand): Classroom { + val currentUser = currentUserResolver.requireTeacherOrAdmin(command.authenticatedSubject) + classroomUserResolver.requireClassroomOwner(currentUser, command.classroomId) + val classroom = classroomRepository.findById(command.classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") @@ -178,34 +204,51 @@ class ClassroomService( * Retrieves a classroom by its id. * * @param classroomId the id of the classroom. + * @param authenticatedSubject JWT subject containing the persisted user id. * @return the matching classroom. - * @throws ResponseStatusException if the classroom does not exist. + * @throws ResponseStatusException if the user is not a member of the classroom or the classroom does not exist. */ @Transactional(readOnly = true) - fun getClassroomById(classroomId: Long): Classroom = - classroomRepository.findById(classroomId).orElse(null) + fun getClassroomById(classroomId: Long, authenticatedSubject: String): Classroom { + val user = currentUserResolver.requireUser(authenticatedSubject) + classroomUserResolver.requireClassroomMember(user, classroomId) + + val classroom = classroomRepository.findById(classroomId).orElse(null) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + return classroom + } + /** * Retrieves all classrooms. * + * @param authenticatedSubject JWT subject containing the persisted user id. * @return a list of all classroom entities. */ @Transactional(readOnly = true) - fun getClassrooms(): List = - classroomRepository.findAll() + fun getClassrooms(authenticatedSubject: String): List { + val user = currentUserResolver.requireUser(authenticatedSubject) + val userId = requireNotNull(user.id) { "Authenticated user is missing an id" } + + return classroomRepository.findAllByUserId(userId) + } /** * Deletes a classroom by its id. * * @param classroomId the id of the classroom to remove. - * @throws ResponseStatusException if the classroom does not exist. + * @param authenticatedSubject JWT subject containing the persisted user id. + * @throws ResponseStatusException if the user does not own the classroom or the classroom does not exist. */ @Transactional - fun deleteClassroom(classroomId: Long) { + fun deleteClassroom(classroomId: Long, authenticatedSubject: String) { + val user = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) + classroomUserResolver.requireClassroomOwner(user, classroomId) + if (!classroomRepository.existsById(classroomId)) { throw ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") } + classroomRepository.deleteById(classroomId) } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt index e814bf04..0a55ce39 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt @@ -2,6 +2,8 @@ package edu.ntnu.idi.idatt.backend.classroom.infrastructure import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.data.jpa.repository.Query +import org.springframework.data.repository.query.Param import org.springframework.stereotype.Repository @Repository @@ -21,4 +23,20 @@ interface ClassroomRepository : JpaRepository { * explicit classroom id. */ fun findFirstByOwnerTeacherIdOrderByIdAsc(ownerTeacherId: Long): Classroom? + + /** + * Finds all classrooms that the given user is member of. + * + * @param userId the id of the user. + * @return a list of classrooms where the user is either a teacher or a pupil. + */ + @Query( + """ + SELECT DISTINCT c FROM Classroom c + LEFT JOIN c.teacherMemberships tm + LEFT JOIN c.pupilMemberships pm + WHERE tm.teacher.id = :userId OR pm.pupil.id = :userId + """ + ) + fun findAllByUserId(@Param("userId") userId: Long): List } diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt index fff8ca52..d5bd1f03 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/iam/application/ClassroomUserResolver.kt @@ -80,6 +80,26 @@ class ClassroomUserResolver( * @throws ResponseStatusException 403 if [user] is not a member of the classroom */ fun requireClassroomMember(user: User, classroomId: Long): Classroom { + val classroom = classroomRepository.findById(classroomId) + .orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") + } + + val userId = requireNotNull(user.id) + + val isOwner = classroom.ownerTeacherId == userId + val isTeacherMember = classroom.teacherMemberships.any { + it.id.teacherUserId == userId + } + val isPupilMember = classroom.pupilMemberships.any { + it.id.pupilUserId == userId + } + + if (!isOwner && !isTeacherMember && !isPupilMember) { + throw ResponseStatusException(HttpStatus.FORBIDDEN, "Access requires a member of the classroom") + } + + return classroom TODO("Not implemented: requires classroom membership table") } diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt index c5b304b9..c5ed63b7 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt @@ -214,6 +214,8 @@ class ClassroomIntegrationTests { contentType = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, "Bearer ${pupilAccessToken("listuser", "secret123")}") content = """{"classroomCode":"LIST1"}""" + }.andExpect { + status { isOk() } } mockMvc.get("/api/v1/classrooms") { @@ -231,11 +233,17 @@ class ClassroomIntegrationTests { val pupil = userRepository.save(activePupil(username = "detailuser")) val token = pupilAccessToken(username = "detailuser", password = "secret123") + mockMvc.post("/api/v1/classrooms/join") { + with(csrf()) + contentType = MediaType.APPLICATION_JSON + header(HttpHeaders.AUTHORIZATION, "Bearer $token") + content = """{"classroomCode":"DETAIL1"}""" + }.andExpect { + status { isOk() } + } + mockMvc.get("/api/v1/classrooms/${classroom.id}") { - header( - HttpHeaders.AUTHORIZATION, - "Bearer $token" - ) + header(HttpHeaders.AUTHORIZATION, "Bearer $token") }.andExpect { status { isOk() } jsonPath("$.id") { value(classroom.id.toInt()) } @@ -271,8 +279,8 @@ class ClassroomIntegrationTests { fun `teacher can update classroom`() { val classroom = createClassroom("UPDATE1") - val teacher = userRepository.save(activeTeacher("teacher-update@test.com")) - val token = teacherPortalAccessToken("teacher-update@test.com", "secret123") + val ownerEmail = "owner-UPDATE1@example.com" + val token = teacherPortalAccessToken(ownerEmail, "secret123") val request = """ { diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt index 43c618e8..7d6a7278 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomServiceTest.kt @@ -12,6 +12,7 @@ import edu.ntnu.idi.idatt.backend.classroom.domain.ClassroomStatus import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository +import edu.ntnu.idi.idatt.backend.iam.application.ClassroomUserResolver 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 @@ -34,6 +35,7 @@ import org.mockito.Mockito.any class ClassroomServiceTest { private lateinit var classroomRepository: ClassroomRepository private lateinit var currentUserResolver: CurrentUserResolver + private lateinit var classroomUserResolver: ClassroomUserResolver private lateinit var pupilGameProgressRepository: PupilGameProgressRepository private lateinit var classroomService: ClassroomService private lateinit var userRepository: UserRepository @@ -44,12 +46,14 @@ class ClassroomServiceTest { classroomRepository = mock(ClassroomRepository::class.java) currentUserResolver = mock(CurrentUserResolver::class.java) userRepository = mock(UserRepository::class.java) + classroomUserResolver = mock(ClassroomUserResolver::class.java) pupilGameProgressRepository = mock(PupilGameProgressRepository::class.java) eventPublisher = mock(ApplicationEventPublisher::class.java) classroomService = ClassroomService( classroomRepository, currentUserResolver, userRepository, + classroomUserResolver, pupilGameProgressRepository, eventPublisher, ) @@ -240,17 +244,19 @@ class ClassroomServiceTest { verify(classroomRepository).findByJoinCode("ABC123") } - // approve pupils @Test fun `should be able to approve students`() { val classroom = Classroom(id = 1, ownerTeacherId = 2, title = "class", description = "description", joinCode = "ABC123", status = ClassroomStatus.ACTIVE) val pupil = User(id = 3, email = null, username = "pupil", passwordHash = "password", role = UserRole.PUPIL, status = UserStatus.ACTIVE) + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) + classroom.addTeacher(teacher) classroom.addPupilMembership(pupil) `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) - classroomService.approvePupil(1, 3) + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) + classroomService.approvePupil(1, 3, "teacher") verify(classroomRepository).findById(1) verify(classroomRepository).save(classroom) @@ -261,10 +267,12 @@ class ClassroomServiceTest { @Test fun `should throw when approving pupil in non-existing classroom`() { + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.empty()) val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { - classroomService.approvePupil(1, 3) + classroomService.approvePupil(1, 3, "teacher") } assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) @@ -273,29 +281,16 @@ class ClassroomServiceTest { @Test fun `should remove pupil from classroom`() { - val classroom = Classroom( - id = 1, - ownerTeacherId = 2, - title = "classroom", - description = "description", - joinCode = "ABC123", - status = ClassroomStatus.ACTIVE - ) - - val pupil = User( - id = 3, - email = "pupil@test.com", - username = "pupil", - passwordHash = "password", - role = UserRole.PUPIL, - status = UserStatus.ACTIVE - ) + val classroom = Classroom(id = 1, ownerTeacherId = 2, title = "class", description = "description", joinCode = "ABC123", status = ClassroomStatus.ACTIVE) + val pupil = User(id = 3, email = null, username = "pupil", passwordHash = "password", role = UserRole.PUPIL, status = UserStatus.ACTIVE) + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) + classroom.addTeacher(teacher) classroom.addPupilMembership(pupil) `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) - - classroomService.removePupil(1, 3) + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) + classroomService.removePupil(1, 3, "teacher") verify(classroomRepository).findById(1) verify(classroomRepository).save(classroom) @@ -305,10 +300,13 @@ class ClassroomServiceTest { @Test fun `should throw when removing pupil from non-existing classroom`() { + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.empty()) + val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { - classroomService.removePupil(1, 3) + classroomService.removePupil(1, 3, "teacher") } assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) @@ -317,35 +315,14 @@ class ClassroomServiceTest { @Test fun `should update classroom title, description and teachers`() { - val classroom = Classroom( - id = 1, - ownerTeacherId = 2, - title = "old", - description = "old", - joinCode = "ABC123", - status = ClassroomStatus.ACTIVE - ) - - val teacher = User( - id = 10, - email = "teacher@test.com", - username = "teacher", - passwordHash = "password", - role = UserRole.TEACHER, - status = UserStatus.ACTIVE - ) + val classroom = Classroom(id = 1, ownerTeacherId = 2, title = "old", description = "old", joinCode = "ABC123", status = ClassroomStatus.ACTIVE) + val teacher = User(id = 10, email = "teacher@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE) `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) `when`(userRepository.findAllByEmailIgnoreCaseIn(listOf("teacher@test.com"))).thenReturn(listOf(teacher)) `when`(classroomRepository.save(any())).thenAnswer { it.arguments[0] } - val command = UpdateClassroomCommand( - classroomId = 1, - title = "new", - description = "new", - teacherEmails = listOf("teacher@test.com"), - authenticatedSubject = "10" - ) + val command = UpdateClassroomCommand(classroomId = 1, title = "new", description = "new", teacherEmails = listOf("teacher@test.com"), authenticatedSubject = "10") val result = classroomService.updateClassroom(command) @@ -358,81 +335,72 @@ class ClassroomServiceTest { @Test fun `should throw when updating classroom with unknown teacher emails`() { - val classroom = Classroom( - id = 1, - ownerTeacherId = 2, - title = "old", - description = "old", - joinCode = "ABC123", - status = ClassroomStatus.ACTIVE - ) + val classroom = Classroom(id = 1, ownerTeacherId = 2, title = "old", description = "old", joinCode = "ABC123", status = ClassroomStatus.ACTIVE) + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) + + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) + `when`(classroomUserResolver.requireClassroomOwner(teacher, 1L)).thenAnswer { } `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.of(classroom)) `when`(userRepository.findAllByEmailIgnoreCaseIn(listOf("missing@test.com"))).thenReturn(emptyList()) - val command = UpdateClassroomCommand( - classroomId = 1, - title = "new", - description = "new", - teacherEmails = listOf("missing@test.com"), - authenticatedSubject = "2" - ) + val command = UpdateClassroomCommand(classroomId = 1, title = "new", description = "new", teacherEmails = listOf("missing@test.com"), authenticatedSubject = "2") val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { classroomService.updateClassroom(command) } assertEquals(HttpStatus.CONFLICT, exception.statusCode) - verify(classroomRepository, never()).save(any()) + verify(classroomRepository, never()).save(any(Classroom::class.java)) } @Test fun `should return all classrooms`() { val classrooms = listOf( - Classroom( - id = 1, - ownerTeacherId = 2, - title = "classroom 1", - description = "description", - joinCode = "ABC123", - status = ClassroomStatus.ACTIVE - ), - Classroom( - id = 3, - ownerTeacherId = 4, - title = "classroom 2", - description = "description", - joinCode = "123ABC", - status = ClassroomStatus.ACTIVE - ) + Classroom(id = 1, ownerTeacherId = 2, title = "classroom 1", description = "description", joinCode = "ABC123", status = ClassroomStatus.ACTIVE), + Classroom(id = 3, ownerTeacherId = 2, title = "classroom 2", description = "description", joinCode = "123ABC", status = ClassroomStatus.ACTIVE) ) + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) - `when`(classroomRepository.findAll()).thenReturn(classrooms) + `when`(currentUserResolver.requireUser("2")).thenReturn(teacher) - val result = classroomService.getClassrooms() + `when`(classroomRepository.findAllByUserId(2)).thenReturn(classrooms) + + val result = classroomService.getClassrooms("2") assertEquals(2, result.size) - verify(classroomRepository).findAll() + verify(classroomRepository).findAllByUserId(2) } @Test fun `should delete classroom`() { + val classroom = Classroom(id = 1, ownerTeacherId = 2, title = "old", description = "old", joinCode = "ABC123", status = ClassroomStatus.ACTIVE) + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) + + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) + `when`(classroomUserResolver.requireClassroomOwner(teacher, 1L)).thenReturn(classroom) + `when`(classroomRepository.existsById(1)).thenReturn(true) - classroomService.deleteClassroom(1) + classroomService.deleteClassroom(1, "teacher") verify(classroomRepository).deleteById(1) } @Test - fun `should throw when deleteting non-existing classroom`() { + fun `should throw when deleting non-existing classroom`() { + val teacher = User(id = 2, email = "test@test.com", username = "teacher", passwordHash = "password", role = UserRole.TEACHER, status = UserStatus.ACTIVE ) + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) + `when`(classroomRepository.findById(1)).thenReturn(java.util.Optional.empty()) + + `when`(classroomRepository.existsById(1)).thenReturn(false) val exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { - classroomService.deleteClassroom(1) + classroomService.deleteClassroom(1, "teacher") } assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) - verify(classroomRepository, never()).deleteById(any()) + verify(classroomRepository, never()).deleteById(1) } } From 19f64973ddbebbbd15c7f4fb791fb896cab3a020 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Tue, 21 Apr 2026 15:02:20 +0200 Subject: [PATCH 22/26] update file name --- ...eachers_table.sql => V14__create_classroom_teachers_table.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/main/resources/db/migration/{V13__create_classroom_teachers_table.sql => V14__create_classroom_teachers_table.sql} (100%) diff --git a/src/main/resources/db/migration/V13__create_classroom_teachers_table.sql b/src/main/resources/db/migration/V14__create_classroom_teachers_table.sql similarity index 100% rename from src/main/resources/db/migration/V13__create_classroom_teachers_table.sql rename to src/main/resources/db/migration/V14__create_classroom_teachers_table.sql From c549ade143fea325ebc4a35aea705d15fd2c82d2 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Tue, 21 Apr 2026 15:03:22 +0200 Subject: [PATCH 23/26] fix --- .../backend/classroom/infrastructure/ClassroomRepository.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt index 77b20a81..e88f2d1e 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/infrastructure/ClassroomRepository.kt @@ -40,7 +40,8 @@ interface ClassroomRepository : JpaRepository { """ ) fun findAllByUserId(@Param("userId") userId: Long): List - + + /** * Returns all classrooms with the average total score across their pupils. * * Classrooms without matching pupil progress rows are included with an From 33a7605efea949b46957e0be8a23bd26a9e34134 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Tue, 21 Apr 2026 15:10:29 +0200 Subject: [PATCH 24/26] fix --- .../idatt/backend/classroom/ClassroomIntegrationTests.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt index a4caab73..e8a6c898 100644 --- a/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt +++ b/src/test/kotlin/edu/ntnu/idi/idatt/backend/classroom/ClassroomIntegrationTests.kt @@ -335,7 +335,10 @@ class ClassroomIntegrationTests { mockMvc.post("/api/v1/classrooms/join") { with(csrf()) contentType = MediaType.APPLICATION_JSON - header(HttpHeaders.AUTHORIZATION, "Bearer ${pupilAccessToken("removeuser", "secret123")}") + header( + HttpHeaders.AUTHORIZATION, + "Bearer ${pupilAccessToken("removeuser", "secret123")}" + ) content = """{"classroomCode":"REMOVE1"}""" } @@ -356,7 +359,9 @@ class ClassroomIntegrationTests { ) ?: 0 assertEquals(0, count) + } + @Test fun `repository returns average total score for all classrooms`() { val firstClassroom = createClassroom("AVG101") val secondClassroom = createClassroom("AVG202") @@ -472,3 +477,5 @@ class ClassroomIntegrationTests { status = UserStatus.ACTIVE, ) } + + From 89552fe49dd2a2c106fbc0cbb333db7907fab908 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Tue, 21 Apr 2026 15:47:32 +0200 Subject: [PATCH 25/26] fix --- .../idi/idatt/backend/classroom/application/ClassroomService.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt index 965c2ff9..c746cad5 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/ClassroomService.kt @@ -11,7 +11,6 @@ import edu.ntnu.idi.idatt.backend.iam.application.ClassroomUserResolver 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.application.CurrentUserResolver import edu.ntnu.idi.idatt.backend.iam.domain.UserRole import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus @@ -64,6 +63,7 @@ class ClassroomService( classroom.addTeacher(teacher) return classroomRepository.save(classroom) + } @Transactional(readOnly = true) fun listOwnedClassrooms(authenticatedSubject: String): List { From 8a70a0e4206dc81ea5f39fd3e161ae0908833360 Mon Sep 17 00:00:00 2001 From: Maria <145002050+marikolafs@users.noreply.github.com> Date: Tue, 21 Apr 2026 16:20:44 +0200 Subject: [PATCH 26/26] change get mapping for owned classrom to /owned to avoid conflict --- .../ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt index 4e42c63b..a90ef03b 100644 --- a/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomController.kt @@ -28,7 +28,7 @@ class ClassroomController( .listOwnedClassrooms(currentUser.subject) .map { it.toOwnedClassroomResponse() } - @GetMapping("/{classroomId}") + @GetMapping("/owned/{classroomId}") fun getOwnedClassroom( @AuthenticationPrincipal currentUser: CurrentUser, @PathVariable classroomId: Long,