Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
55f294b
Added map-stops and basic endpoints
Apr 15, 2026
ca77736
refactored for domain structure
Apr 15, 2026
cc547f4
Added javadoc and better names
Apr 15, 2026
bf24623
Merge pull request #18 from idatt2106-v26-04/main
kso Apr 15, 2026
633a538
Changed structure
Apr 15, 2026
0350490
finished adding mapStops and PupilStopProgress implementations
Apr 16, 2026
9d27ef9
fixed dum mistake in mapStops
Apr 16, 2026
2c579e0
Added data-seeding for map-stops
Apr 16, 2026
79f5fe5
prepare for merge with main
Apr 17, 2026
deb7bd9
Merge remote-tracking branch 'origin/main' into feat/map-stops
Apr 17, 2026
90f6c24
integrated mapStops with classrooms with stopprogressSeeder
Apr 17, 2026
b155660
Merge in map-stops branch
sindrelm Apr 17, 2026
d7c7240
Add PupilGameProgress class
sindrelm Apr 17, 2026
f9487ba
Add docs to PupilGameProgress
sindrelm Apr 17, 2026
228d483
Add PupilGameProgressRepository
sindrelm Apr 17, 2026
5129aa4
start on LeaderboardService2
sindrelm Apr 17, 2026
492f211
Add function to find a Users classroom in CurrentUserResolver
sindrelm Apr 20, 2026
cb6a2a0
Add leaderboard service
sindrelm Apr 20, 2026
494f8e6
Add db migration schema
sindrelm Apr 20, 2026
3b01c84
Move leaderboard ordering logic into repo class
sindrelm Apr 20, 2026
e6b2cbd
Finish api endpoints
sindrelm Apr 20, 2026
25b83c8
Revert "Merge in map-stops branch"
sindrelm Apr 20, 2026
478ecc9
Create PupilGameProgress entry when a pupil joins a classroom
sindrelm Apr 20, 2026
1425a57
Remove spacing
sindrelm Apr 20, 2026
77c6828
Fix test
sindrelm Apr 20, 2026
fa6ce39
Add bootstrap data in PupilGameProgress table
sindrelm Apr 20, 2026
aaedd2b
Fix merge conflict
sindrelm Apr 20, 2026
702ab8d
Remove underscores from func names
sindrelm Apr 20, 2026
bd2a071
Fix merge conflict
sindrelm Apr 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ 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.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.mapstops.domain.MapStop
import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository
import edu.ntnu.idi.idatt.backend.game.tasks.domain.Task
Expand Down Expand Up @@ -59,6 +62,7 @@ class DevDataBootstrap(
private val pupilProfileRepository: PupilProfileRepository,
private val userAvatarRepository: UserAvatarRepository,
private val refreshTokenRepository: RefreshTokenRepository,
private val pupilGameProgressRepository: PupilGameProgressRepository,
private val passwordEncoder: PasswordEncoder,
private val mapStopBootstrap: MapStopBootstrap,
private val mapStopsRepository: MapStopsRepository,
Expand Down Expand Up @@ -97,10 +101,33 @@ class DevDataBootstrap(
joinCode = "CLASS42",
)
seedClassroomMembership(sampleClassroom, pupilAda, "Ada")
seedClassroomMembership(sampleClassroom, pupilNoah, "Noah")
seedPupilProfile(pupilAda, "Ada", sampleClassroom.id)
seedPupilProfile(pupilNoah, "Noah", null)
seedPupilProfile(pupilNoah, "Noah", sampleClassroom.id)
seedPupilAvatar(pupilAda)
seedPupilAvatar(pupilNoah)
seedPupilGameProgress(
pupil = pupilAda,
classroom = sampleClassroom,
totalScore = 240,
totalXp = 480,
currentLevel = 4,
completedStopsCount = 3,
completedTasksCount = 9,
finalBossCompleted = false,
lastActivityAt = Instant.now().minus(2, ChronoUnit.HOURS),
)
seedPupilGameProgress(
pupil = pupilNoah,
classroom = sampleClassroom,
totalScore = 125,
totalXp = 260,
currentLevel = 2,
completedStopsCount = 1,
completedTasksCount = 5,
finalBossCompleted = false,
lastActivityAt = Instant.now().minus(1, ChronoUnit.DAYS),
)

seedRefreshToken(admin, "dev-admin-refresh-token", Instant.now().plus(14, ChronoUnit.DAYS), null)
seedRefreshToken(
Expand Down Expand Up @@ -193,7 +220,10 @@ class DevDataBootstrap(
currentClassroomId: Long?,
) {
val userId = requireNotNull(user.id) { "Pupil seed user must have an id" }
if (pupilProfileRepository.existsById(userId)) {
val existingProfile = pupilProfileRepository.findById(userId).orElse(null)
if (existingProfile != null) {
existingProfile.displayName = displayName
existingProfile.currentClassroomId = currentClassroomId
return
}

Expand All @@ -206,6 +236,52 @@ class DevDataBootstrap(
)
}

private fun seedPupilGameProgress(
pupil: User,
classroom: Classroom,
totalScore: Int,
totalXp: Int,
currentLevel: Int,
completedStopsCount: Int,
completedTasksCount: Int,
finalBossCompleted: Boolean,
lastActivityAt: Instant,
) {
val pupilUserId = requireNotNull(pupil.id) { "Pupil seed user must have an id" }
val classroomId = classroom.id
val existingProgress = pupilGameProgressRepository.findByPupilIdAndClassroom_Id(pupilUserId, classroomId)
if (existingProgress != null) {
existingProgress.updateProgress(
totalScore = totalScore,
totalXp = totalXp,
currentLevel = currentLevel,
completedStopsCount = completedStopsCount,
completedTasksCount = completedTasksCount,
finalBossCompleted = finalBossCompleted,
lastActivityAt = lastActivityAt,
)
return
}

pupilGameProgressRepository.save(
PupilGameProgress(
id = PupilGameProgressId(
pupilUserId = pupilUserId,
classroomId = classroomId,
),
pupil = pupil,
classroom = classroom,
totalScore = totalScore,
totalXp = totalXp,
currentLevel = currentLevel,
completedStopsCount = completedStopsCount,
completedTasksCount = completedTasksCount,
finalBossCompleted = finalBossCompleted,
lastActivityAt = lastActivityAt,
),
)
}

private fun seedPupilAvatar(user: User) {
val userId = requireNotNull(user.id) { "Pupil seed user must have an id" }
if (userAvatarRepository.existsById(userId)) {
Expand Down Expand Up @@ -309,6 +385,11 @@ class DevDataBootstrap(
passingScore = seed.passingScore,
maxScore = seed.maxScore,
)
if (task.id != null) {
task.items.clear()
task.translations.clear()
taskRepository.saveAndFlush(task)
}
applyTaskSeed(task, classroom, teacher, stopId, seed)
taskRepository.save(task)
}
Expand Down Expand Up @@ -350,8 +431,6 @@ class DevDataBootstrap(
task.passingScore = seed.passingScore
task.maxScore = seed.maxScore
task.isPublished = seed.isPublished
task.items.clear()
task.translations.clear()
addTaskTranslations(task, seed.title, seed.introText)
seed.items.forEach { itemSeed ->
val item = TaskItem(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package edu.ntnu.idi.idatt.backend.classroom.application

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.domain.PupilGameProgressId
import edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure.PupilGameProgressRepository
import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver
import org.springframework.context.ApplicationEventPublisher
import org.springframework.http.HttpStatus
Expand All @@ -20,6 +23,7 @@ import java.util.*
class ClassroomService(
private val classroomRepository: ClassroomRepository,
private val currentUserResolver: CurrentUserResolver,
private val pupilGameProgressRepository: PupilGameProgressRepository,
private val eventPublisher: ApplicationEventPublisher,
) {
/**
Expand Down Expand Up @@ -47,6 +51,16 @@ class ClassroomService(

classroom.addPupilMembership(user)
classroomRepository.save(classroom)
pupilGameProgressRepository.save(
PupilGameProgress(
id = PupilGameProgressId(
pupilUserId = userId,
classroomId = classroom.id,
),
pupil = user,
classroom = classroom,
),
)
eventPublisher.publishEvent(PupilJoinedClassroomEvent(pupil = user, classroom = classroom))

return JoinClassroomResult(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,12 @@ interface ClassroomRepository : JpaRepository<Classroom, Long> {
* @return The classroom if found, or null otherwise.
*/
fun findByJoinCode(code: String): Classroom?
}

/**
* Finds the first classroom owned by the given teacher, ordered by id.
*
* This is only suitable as a fallback when the caller has not supplied an
* explicit classroom id.
*/
fun findFirstByOwnerTeacherIdOrderByIdAsc(ownerTeacherId: Long): Classroom?
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package edu.ntnu.idi.idatt.backend.game.gameProgress.domain

import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom
import edu.ntnu.idi.idatt.backend.iam.domain.User
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.MapsId
import jakarta.persistence.Table
import java.io.Serializable
import java.time.Instant

/**
* Aggregated classroom-scoped game progress for a pupil.
*
* This entity is the source of truth for leaderboard-related progress values
* within a classroom. It stores both score-based and XP-based progression,
* the pupil's current level, completion counters, whether the final boss has
* been completed, and the timestamp of the latest recorded activity.
*
* The entity is keyed by the combination of pupil and classroom, which means
* each pupil has one progress record per classroom.
*/
@Entity
@Table(name = "pupil_game_progress")
class PupilGameProgress(
@EmbeddedId
var id: PupilGameProgressId = PupilGameProgressId(),
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@MapsId("pupilUserId")
@JoinColumn(name = "pupil_user_id", nullable = false)
var pupil: User? = null,
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@MapsId("classroomId")
@JoinColumn(name = "classroom_id", nullable = false)
var classroom: Classroom? = null,
@Column(name = "total_score", nullable = false)
var totalScore: Int = 0,
@Column(name = "total_xp", nullable = false)
var totalXp: Int = 0,
@Column(name = "current_level", nullable = false)
var currentLevel: Int = 1,
@Column(name = "completed_stops_count", nullable = false)
var completedStopsCount: Int = 0,
@Column(name = "completed_tasks_count", nullable = false)
var completedTasksCount: Int = 0,
@Column(name = "final_boss_completed", nullable = false)
var finalBossCompleted: Boolean = false,
@Column(name = "last_activity_at", nullable = false)
var lastActivityAt: Instant = Instant.now(),
) {
/**
* Replaces the current aggregated progress snapshot for this pupil in the classroom.
*/
fun updateProgress(
totalScore: Int,
totalXp: Int,
currentLevel: Int,
completedStopsCount: Int,
completedTasksCount: Int,
finalBossCompleted: Boolean,
lastActivityAt: Instant,
) {
this.totalScore = totalScore
this.totalXp = totalXp
this.currentLevel = currentLevel
this.completedStopsCount = completedStopsCount
this.completedTasksCount = completedTasksCount
this.finalBossCompleted = finalBossCompleted
this.lastActivityAt = lastActivityAt
}
}

/**
* Composite identifier for [PupilGameProgress].
*/
@Embeddable
data class PupilGameProgressId(
@Column(name = "pupil_user_id")
val pupilUserId: Long = 0,
@Column(name = "classroom_id")
val classroomId: Long = 0,
) : Serializable
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package edu.ntnu.idi.idatt.backend.game.gameProgress.infrastructure

import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgress
import edu.ntnu.idi.idatt.backend.game.gameProgress.domain.PupilGameProgressId
import org.springframework.data.jpa.repository.JpaRepository

/**
* Repository for pupil game progress.
*/
interface PupilGameProgressRepository : JpaRepository<PupilGameProgress, PupilGameProgressId> {
/**
* Finds the aggregated game progress for a specific pupil in a specific classroom.
*
* @param pupilUserId the pupil user ID
* @param classroomId the classroom ID
* @return the matching progress record, or null if no record exists
*/
fun findByPupilIdAndClassroom_Id(pupilUserId: Long, classroomId: Long): PupilGameProgress?

/**
* Finds all progress records for a classroom.
*
* @param classroomId the classroom ID
* @return all progress records registered for the classroom, ordered for leaderboard display
*/
fun findAllByClassroomIdOrderByTotalScoreDescTotalXpDescCurrentLevelDescLastActivityAtDesc(
classroomId: Long,
): List<PupilGameProgress>
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package edu.ntnu.idi.idatt.backend.iam.application

import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom
import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository
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.infrastructure.UserRepository
import edu.ntnu.idi.idatt.backend.users.profile.infrastructure.PupilProfileRepository
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException
Expand All @@ -15,6 +18,8 @@ import org.springframework.web.server.ResponseStatusException
@Service
class CurrentUserResolver(
private val userRepository: UserRepository,
private val pupilProfileRepository: PupilProfileRepository,
private val classroomRepository: ClassroomRepository,
) {
/**
* Resolves the authenticated user from the JWT subject claim.
Expand Down Expand Up @@ -59,5 +64,43 @@ class CurrentUserResolver(
return user
}

/**
* Resolves a classroom for the authenticated user.
*
* Pupils resolve through `PupilProfile.currentClassroomId`.
* Teachers resolve through the first classroom they own.
*
* Note: teachers can own multiple classrooms. This method therefore only
* works as a fallback when no explicit classroom id is supplied.
*
* @param authenticatedSubject JWT subject containing the persisted user id
* @return resolved classroom
*/
fun getClassroomByUser(authenticatedSubject: String): Classroom {
val user = requireUser(authenticatedSubject)
val userId = requireNotNull(user.id) { "Authenticated user is missing an id" }

return when (user.role) {
UserRole.PUPIL -> {
val pupilProfile = pupilProfileRepository.findById(userId)
.orElseThrow {
ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil profile was not found")
}
val classroomId = pupilProfile.currentClassroomId
?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Pupil has no current classroom")
classroomRepository.findById(classroomId)
.orElseThrow {
ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom was not found")
}
}

UserRole.TEACHER -> classroomRepository.findFirstByOwnerTeacherIdOrderByIdAsc(userId)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Teacher does not own any classroom")

UserRole.ADMIN -> throw ResponseStatusException(
HttpStatus.FORBIDDEN,
"Admins are not associated with a classroom",
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package edu.ntnu.idi.idatt.backend.leaderboard.api

import edu.ntnu.idi.idatt.backend.leaderboard.application.LeaderboardEntry

/**
* Converts ordered classroom leaderboard rows into the public leaderboard payload.
*
* @return response exposed by the leaderboard API
*/
fun List<LeaderboardEntry>.toLeaderboardResponse(): LeaderboardResponse =
LeaderboardResponse(
entries = map { entry ->
LeaderboardEntryResponse(
rank = entry.rank,
pupilUserId = entry.pupilUserId,
displayName = entry.displayName,
totalScore = entry.totalScore,
totalXp = entry.totalXp,
currentLevel = entry.currentLevel,
completedStopsCount = entry.completedStopsCount,
completedTasksCount = entry.completedTasksCount,
finalBossCompleted = entry.finalBossCompleted,
lastActivityAt = entry.lastActivityAt,
)
},
)
Loading