Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class DevDataBootstrap(
private val notebookEntryRepository: NotebookEntryRepository,
private val passwordEncoder: PasswordEncoder,
private val mapStopBootstrap: MapStopBootstrap,
private val medalBootstrap: MedalBootstrap,
private val taskBootstrap: TaskBootstrap,
private val pupilProgressSeedingService: PupilProgressSeedingService,
) : ApplicationRunner {
Expand Down Expand Up @@ -141,6 +142,7 @@ class DevDataBootstrap(
)

mapStopBootstrap.seedAllMapStops()
medalBootstrap.seedAllMedals()
val activeStops = taskBootstrap.seedAllTasks(classroom = sampleClassroom, teacher = teacher)
seedNotebookEntries(
classroom = sampleClassroom,
Expand Down Expand Up @@ -423,4 +425,4 @@ class DevDataBootstrap(
HexFormat.of().formatHex(
MessageDigest.getInstance("SHA-256").digest(rawToken.toByteArray(StandardCharsets.UTF_8)),
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package edu.ntnu.idi.idatt.backend.bootstrap

import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository
import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal
import edu.ntnu.idi.idatt.backend.game.medals.domain.MedalType
import edu.ntnu.idi.idatt.backend.game.medals.repository.MedalRepository
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Component

@Component
@ConditionalOnProperty(name = ["app.bootstrap.enabled"], havingValue = "true")
class MedalBootstrap(
private val medalRepository: MedalRepository,
private val mapStopsRepository: MapStopsRepository,
) {
fun seedAllMedals() {
mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc().forEach { stop ->
val stopId = requireNotNull(stop.id) { "Seeded map stop must have an id" }
val slug = requireNotNull(stop.slug) { "Seeded map stop must have a slug" }
val title = requireNotNull(stop.title) { "Seeded map stop must have a title" }
val code = "${slug}-completion"

if (medalRepository.findByCode(code) == null) {
medalRepository.save(
Medal(
code = code,
title = "$title fullført",
description = "Tildeles når eleven fullfører stop nummer $stopId: $title.",
medalType = MedalType.STOP_COMPLETION,
stop = stop,
iconUrl = null,
),
)
}
}

if (medalRepository.findByCode("example-approval") == null) {
medalRepository.save(
Medal(
code = "example-approval",
title = "Eksempelgodkjenning",
description = "Tildeles når et eksempelinnhold blir godkjent.",
medalType = MedalType.EXAMPLE_APPROVAL,
stop = null,
iconUrl = null,
),
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,27 @@ import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
import edu.ntnu.idi.idatt.backend.game.medals.application.MedalService
import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository
import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository
import java.time.Instant

/**
* Application service that handles progress lookup and state transitions for pupil map stops.
*
* @property progressRepository JPA repository for pupil stop progress records
* @property mapStopRepository Repository for map stop definitions
* @property medalService Service for awarding medals upon stop completion
* @property userRepository Repository for user lookup
* @property classroomRepository Repository for classroom lookup
*/
@Service
class PupilStopProgressService(
private val progressRepository: PupilStopProgressRepository,
private val mapStopRepository: MapStopsRepository
private val mapStopRepository: MapStopsRepository,
private val medalService: MedalService,
private val userRepository: UserRepository,
private val classroomRepository: ClassroomRepository
) {
/**
* Returns all stop progress records for a pupil in a classroom.
Expand Down Expand Up @@ -90,6 +100,10 @@ class PupilStopProgressService(
progress.currentTaskId = null
progress.completedAt = Instant.now()
unlockNextStop(pupilUserId, classroomId, stopId, activeStops)

val pupil = userRepository.findById(pupilUserId).orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "Pupil not found") }
val classroom = classroomRepository.findById(classroomId).orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found") }
medalService.awardStopMedal(pupil, classroom, stopId)
}
}
command.currentTaskId?.let { progress.currentTaskId = it }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package edu.ntnu.idi.idatt.backend.game.medals.api

import edu.ntnu.idi.idatt.backend.game.medals.application.MedalService
import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal
import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal
import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver
import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser
import org.springframework.http.HttpStatus
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException

/**
* API controller for pupil medal operations.
*
* @property medalService Service for managing medal logic
* @property currentUserResolver Resolver for authenticated user and classroom context
*/
@RestController
@RequestMapping("/api/v1/pupil/medals")
class MedalsController(
private val medalService: MedalService,
private val currentUserResolver: CurrentUserResolver
) {
/**
* Retrieves an overview of all medals and whether the current pupil has earned them.
*
* @param currentUser the authenticated principal
* @return a response containing all medals and their earned status
*/
@GetMapping
fun getMedals(@AuthenticationPrincipal currentUser: CurrentUser): MedalOverviewResponse {
val pupil = currentUserResolver.requirePupil(currentUser.subject)
val classroom = currentUserResolver.getClassroomByUser(currentUser)

val allMedals = medalService.getAllMedals()
val earnedMedals = medalService.getPupilMedals(pupil, classroom)

val earnedMedalIds = earnedMedals.map { it.medal.id }.toSet()

return MedalOverviewResponse(
medals = allMedals.map { medal ->
MedalEntry(
medal = medal,
earned = earnedMedalIds.contains(medal.id)
)
}
)
}

/**
* Retrieves detailed information about a specific medal.
*
* @param id the ID of the medal to retrieve
* @return the medal details
* @throws ResponseStatusException 404 if the medal is not found
*/
@GetMapping("/{id}")
fun getMedal(@PathVariable id: Long): Medal {
return medalService.getMedalById(id)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Medal not found")
}
}

/**
* Response containing an overview of medals.
*
* @property medals list of medal entries
*/
data class MedalOverviewResponse(
val medals: List<MedalEntry>
)

/**
* An entry in the medal overview, combining medal info with earned status.
*
* @property medal the medal definition
* @property earned whether the pupil has earned this medal
*/
data class MedalEntry(
val medal: Medal,
val earned: Boolean
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package edu.ntnu.idi.idatt.backend.game.medals.application

import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal
import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal
import edu.ntnu.idi.idatt.backend.game.medals.repository.MedalRepository
import edu.ntnu.idi.idatt.backend.game.medals.repository.PupilMedalRepository
import edu.ntnu.idi.idatt.backend.iam.domain.User
import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.stereotype.Service
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.TransactionDefinition
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionTemplate
import java.util.stream.Collectors

/**
* Application service for managing medals and awarding them to pupils.
*
* @property medalRepository Repository for medal definitions
* @property pupilMedalRepository Repository for pupil-earned medals
*/
@Service
class MedalService(
private val medalRepository: MedalRepository,
private val pupilMedalRepository: PupilMedalRepository,
transactionManager: PlatformTransactionManager,
) {
private val awardTransaction = TransactionTemplate(transactionManager).apply {
propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRES_NEW
}

/**
* Retrieves a medal by its ID.
*
* @param id the ID of the medal to retrieve
* @return the medal if found, or null otherwise
*/
@Transactional(readOnly = true)
fun getMedalById(id: Long): Medal? = medalRepository.findById(id).orElse(null)

/**
* Retrieves all available medal definitions.
*
* @return a list of all medals
*/
@Transactional(readOnly = true)
fun getAllMedals(): List<Medal> = medalRepository.findAll()

/**
* Retrieves all medals earned by a specific pupil in a specific classroom.
*
* @param pupil the pupil whose medals to retrieve
* @param classroom the classroom context
* @return a list of earned medals
*/
@Transactional(readOnly = true)
fun getPupilMedals(pupil: User, classroom: Classroom): List<PupilMedal> {
val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" }
val classroomId = requireNotNull(classroom.id) { "Classroom is missing an id" }
return pupilMedalRepository.findAllByPupilIdAndClassroomId(pupilId, classroomId).collect(Collectors.toList())
}

/**
* Awards a stop-related medal to a pupil if they haven't already earned it.
*
* @param pupil the pupil to award the medal to
* @param classroom the classroom context
* @param stopId the ID of the stop that triggers the medal
*/
fun awardStopMedal(pupil: User, classroom: Classroom, stopId: Long) {
val medal = medalRepository.findByStopId(stopId) ?: return
val pupilId = requireNotNull(pupil.id) { "Pupil is missing an id" }
val classroomId = requireNotNull(classroom.id) { "Classroom is missing an id" }
if (!pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(pupilId, classroomId, medal.id)) {
try {
awardTransaction.executeWithoutResult {
pupilMedalRepository.saveAndFlush(
PupilMedal(
pupil = pupil,
classroom = classroom,
medal = medal,
awardedReason = "Completed stop ${medal.title}"
)
)
}
} catch (exception: DataIntegrityViolationException) {
val alreadyAwarded = pupilMedalRepository.existsByPupilIdAndClassroomIdAndMedalId(
pupilId,
classroomId,
medal.id,
)
if (!alreadyAwarded) {
throw exception
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package edu.ntnu.idi.idatt.backend.game.medals.domain

import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop
import jakarta.persistence.*

/**
* Represents a medal that can be earned by a pupil.
*
* @property id Unique identifier for the medal.
* @property code Unique code identifying the medal (e.g., "stop-1-completion").
* @property title Human-readable title of the medal.
* @property description Detailed description of how to earn the medal.
* @property medalType The type of medal (e.g., [MedalType.STOP_COMPLETION]).
* @property stop The map stop associated with this medal, if any.
* @property iconUrl URL to the icon representing the medal.
*/
@Entity
@Table(name = "medals")
class Medal(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,

@Column(nullable = false, unique = true)
val code: String,

@Column(nullable = false)
val title: String,

@Column
val description: String?,

@Enumerated(EnumType.STRING)
@Column(nullable = false)
val medalType: MedalType,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "stop_id")
val stop: MapStop?,

@Column
val iconUrl: String?
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package edu.ntnu.idi.idatt.backend.game.medals.domain

enum class MedalType {
STOP_COMPLETION,
EXAMPLE_APPROVAL
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package edu.ntnu.idi.idatt.backend.game.medals.domain

import edu.ntnu.idi.idatt.backend.iam.domain.User
import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom
import jakarta.persistence.*
import java.time.Instant

/**
* Represents a medal earned by a pupil within a specific classroom.
*
* @property id Unique identifier for the award record.
* @property pupil The pupil who earned the medal.
* @property classroom The classroom context in which the medal was earned.
* @property medal The medal that was awarded.
* @property awardedReason Reason why the medal was awarded.
* @property awardedAt The timestamp when the medal was awarded.
*/
@Entity
@Table(name = "pupil_medals")
class PupilMedal(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "pupil_user_id", nullable = false)
val pupil: User,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "classroom_id", nullable = false)
val classroom: Classroom,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "medal_id", nullable = false)
val medal: Medal,

@Column
val awardedReason: String?,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a bit redundant. Similar to medal_description


@Column(nullable = false)
val awardedAt: Instant = Instant.now()
)
Loading