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 040363c6..edad66cc 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,15 +1,57 @@ 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.Classroom import edu.ntnu.idi.idatt.backend.classroom.application.OwnedClassroomSummary +/** + * 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, + description = description, + 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 +): UpdateClassroomCommand = + UpdateClassroomCommand( + classroomId = id, + title = title, + description = description, + teacherEmails = teacherEmails, + 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, @@ -18,6 +60,51 @@ 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, + title = title, + description = description, + joinCode = joinCode ?: "", + 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, + title = title, + description = description, + joinCode = joinCode ?: "", + + teachers = teacherMemberships.mapNotNull { membership -> + val teacher = membership.teacher ?: return@mapNotNull null + + ClassroomTeacherResponse( + userId = teacher.id ?: return@mapNotNull null, + email = teacher.email, + ) + }, + + pupils = pupilMemberships.mapNotNull { membership -> + val pupil = membership.pupil ?: return@mapNotNull null + + ClassroomPupilResponse( + userId = pupil.id ?: return@mapNotNull null, + displayName = pupil.username ?: "Unknown", + ) + } + ) + fun OwnedClassroomSummary.toOwnedClassroomResponse(): OwnedClassroomResponse = OwnedClassroomResponse( id = id, 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 7a07d514..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 @@ -4,6 +4,7 @@ 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.* import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping @@ -27,7 +28,7 @@ class ClassroomController( .listOwnedClassrooms(currentUser.subject) .map { it.toOwnedClassroomResponse() } - @GetMapping("/{classroomId}") + @GetMapping("/owned/{classroomId}") fun getOwnedClassroom( @AuthenticationPrincipal currentUser: CurrentUser, @PathVariable classroomId: Long, @@ -36,6 +37,32 @@ class ClassroomController( .getOwnedClassroom(currentUser.subject, classroomId) .toOwnedClassroomResponse() + /** + * 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, + @AuthenticationPrincipal currentUser: CurrentUser, + ): ClassroomResponse = + classroomService.createClassroom( + request.toCommand(currentUser.subject) + ).toResponse() + + /** + * Retrieves all classrooms the authenticated user is a member of. + * + * @param currentUser the authenticated user extracted from the security context. + * @return a list of classrooms accessible to the user. + */ + @GetMapping + fun getClassrooms(@AuthenticationPrincipal currentUser: CurrentUser): List = + classroomService.getClassrooms(currentUser.subject).map { it.toResponse() } + /** * Endpoint for joining a classroom. * @@ -48,5 +75,83 @@ 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. + * + * @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, + @AuthenticationPrincipal currentUser: CurrentUser, + ): ClassroomDetailResponse = + classroomService.getClassroomById(id, currentUser.subject).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, + @RequestBody @Valid request: UpdateClassroomRequest, + @AuthenticationPrincipal currentUser: CurrentUser, + ): ClassroomResponse = + classroomService.updateClassroom( + request.toCommand(id, currentUser.subject) + ).toResponse() + + /** + * 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, currentUser.subject) + } + + /** + * 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. + * @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.deleteClassroom(id, currentUser.subject) + } } 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..34e2236f --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomDetailResponse.kt @@ -0,0 +1,20 @@ +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, + val description: String?, + val joinCode: String, + 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/ClassroomPupilResponse.kt b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt new file mode 100644 index 00000000..bf32893e --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomPupilResponse.kt @@ -0,0 +1,12 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +/** + * 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 new file mode 100644 index 00000000..6cd92255 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomResponse.kt @@ -0,0 +1,18 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +/** + * 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?, + 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..4a5ca51d --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/ClassroomTeacherResponse.kt @@ -0,0 +1,12 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +/** + * 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 new file mode 100644 index 00000000..5512335f --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/CreateClassroomRequest.kt @@ -0,0 +1,18 @@ +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) + 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 new file mode 100644 index 00000000..87299f8c --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/api/UpdateClassroomRequest.kt @@ -0,0 +1,19 @@ +package edu.ntnu.idi.idatt.backend.classroom.api + +import jakarta.validation.constraints.NotBlank + +/** + * 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 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 680fc86e..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 @@ -7,8 +7,10 @@ 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.game.tasks.infrastructure.TaskRepository +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.domain.UserRole import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus @@ -20,17 +22,49 @@ 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 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 taskRepository: TaskRepository, private val eventPublisher: ApplicationEventPublisher, ) { + + /** + * 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) + 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) + } + @Transactional(readOnly = true) fun listOwnedClassrooms(authenticatedSubject: String): List { val user = currentUserResolver.requireTeacherOrAdmin(authenticatedSubject) @@ -77,8 +111,13 @@ 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) { throw ResponseStatusException(HttpStatus.CONFLICT, "Cannot join an inactive classroom") } @@ -104,11 +143,158 @@ class ClassroomService( return JoinClassroomResult( classroomId = classroom.id, classroomTitle = classroom.title, - membershipStatus = "PENDING", + membershipStatus = ClassroomPupilStatus.PENDING.name, message = "Join request submitted", ) } + /** + * Approves a pending pupil membership in a classroom. + * + * @param classroomId the id of the classroom. + * @param pupilUserId the id of the pupil to approve. + * @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, 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") + + try { + classroom.approvePupil(pupilUserId) + } catch (e: IllegalArgumentException) { + throw ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil not found in classroom") + } + + 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. + * @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, 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") + + try { + classroom.removePupil(pupilUserId) + } catch (e: IllegalArgumentException) { + throw ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil not found in classroom") + } + + 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 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") + + 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() + + teachers.forEach { teacher -> + classroom.addTeacher(teacher) + } + + return classroomRepository.save(classroom) + } + + /** + * 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 user is not a member of the classroom or the classroom does not exist. + */ + @Transactional(readOnly = true) + 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(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. + * @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, 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) + } + + /** + * 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()) { @@ -117,6 +303,15 @@ 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() + private fun toOwnedClassroomSummary(classroom: Classroom): OwnedClassroomSummary = OwnedClassroomSummary( id = classroom.id, 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..d5b1b9d8 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/CreateClassroomCommand.kt @@ -0,0 +1,16 @@ +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?, + 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..ae2639eb --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/application/UpdateClassroomCommand.kt @@ -0,0 +1,20 @@ +package edu.ntnu.idi.idatt.backend.classroom.application + +/** + * 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?, + 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 5d4fdec1..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 @@ -40,7 +32,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 +44,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 +81,92 @@ 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") + + membership.status = ClassroomPupilStatus.ACTIVE + 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 + } + + if (!removed) { + throw IllegalArgumentException("Pupil $pupilUserId is not a member of this 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) + + teacherMemberships.add( + ClassroomTeacherMembership( + id = ClassroomTeacherMembershipId( + classroomId = id, + teacherUserId = userId, + ), + classroom = this, + teacher = teacher, + ) + ) + } + + /** + * 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 new file mode 100644 index 00000000..2b0e5390 --- /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.* + +/** + * 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( + @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") + var teacher: User? = null, +) + 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..d02c3e45 --- /dev/null +++ b/src/main/kotlin/edu/ntnu/idi/idatt/backend/classroom/domain/ClassroomTeacherMembershipId.kt @@ -0,0 +1,19 @@ +package edu.ntnu.idi.idatt.backend.classroom.domain + +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") + var classroomId: Long = 0, + @Column(name = "teacher_user_id") + var teacherUserId: Long = 0, +) : Serializable + 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 a1d01615..9897c162 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 @@ -3,6 +3,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 @@ -25,6 +27,22 @@ interface ClassroomRepository : JpaRepository { fun findAllByOwnerTeacherIdOrderByTitleAscIdAsc(ownerTeacherId: Long): List + /** + * 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 + /** * Returns all classrooms with the average total score across their pupils. * 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..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 @@ -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,27 @@ 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") } } \ 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/V14__create_classroom_teachers_table.sql b/src/main/resources/db/migration/V14__create_classroom_teachers_table.sql new file mode 100644 index 00000000..c726523d --- /dev/null +++ b/src/main/resources/db/migration/V14__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 users(id) ON DELETE CASCADE +); \ No newline at end of file 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 0ec131d4..66361c21 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 @@ -27,8 +27,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 @@ -243,6 +245,160 @@ 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"}""" + }.andExpect { + status { isOk() } + } + + 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.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") + }.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 ownerEmail = "owner-UPDATE1@example.com" + val token = teacherPortalAccessToken(ownerEmail, "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) + } + @Test fun `repository returns average total score for all classrooms`() { val firstClassroom = createClassroom("AVG101") @@ -296,6 +452,7 @@ class ClassroomIntegrationTests { assertEquals(15.0, averages.first { it.classroomId == firstClassroom.id }.averageTotalScore) assertEquals(30.0, averages.first { it.classroomId == secondClassroom.id }.averageTotalScore) assertEquals(0.0, averages.first { it.classroomId == emptyClassroom.id }.averageTotalScore) + } private fun createClassroom(classroomCode: String): Classroom { @@ -312,6 +469,7 @@ class ClassroomIntegrationTests { ), ) } + private fun pupilAccessToken(username: String, password: String): String = jsonMapper.readTree( mockMvc.post("/api/v1/auth/pupil/login") { @@ -357,3 +515,5 @@ class ClassroomIntegrationTests { status = UserStatus.ACTIVE, ) } + + 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 0059d4c9..ad73dd55 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 @@ -10,11 +12,13 @@ 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.game.tasks.infrastructure.TaskRepository 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 @@ -27,31 +31,66 @@ import org.mockito.Mockito.`when` import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException +import org.mockito.Mockito.any 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 taskRepository: TaskRepository private lateinit var classroomService: ClassroomService + private lateinit var userRepository: UserRepository private lateinit var eventPublisher: ApplicationEventPublisher @BeforeEach fun setup() { 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) taskRepository = mock(TaskRepository::class.java) eventPublisher = mock(ApplicationEventPublisher::class.java) classroomService = ClassroomService( classroomRepository, currentUserResolver, + userRepository, + classroomUserResolver, pupilGameProgressRepository, taskRepository, eventPublisher, ) } + @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 fun `should add user to classroom`() { val classroomCode = "ABC12" @@ -208,4 +247,164 @@ class ClassroomServiceTest { verify(classroomRepository).findByJoinCode("ABC123") } + + @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)) + + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) + classroomService.approvePupil(1, 3, "teacher") + + 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`() { + 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, "teacher") + } + + 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 = "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)) + `when`(currentUserResolver.requireTeacherOrAdmin("teacher")).thenReturn(teacher) + classroomService.removePupil(1, 3, "teacher") + + 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`() { + 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, "teacher") + } + + 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) + 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 exception = org.junit.jupiter.api.Assertions.assertThrows(ResponseStatusException::class.java) { + classroomService.updateClassroom(command) + } + + assertEquals(HttpStatus.CONFLICT, exception.statusCode) + 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 = 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`(currentUserResolver.requireUser("2")).thenReturn(teacher) + + `when`(classroomRepository.findAllByUserId(2)).thenReturn(classrooms) + + val result = classroomService.getClassrooms("2") + + assertEquals(2, result.size) + 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, "teacher") + + verify(classroomRepository).deleteById(1) + } + + @Test + 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, "teacher") + } + + assertEquals(HttpStatus.NOT_FOUND, exception.statusCode) + verify(classroomRepository, never()).deleteById(1) + } }