Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -60,6 +60,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,
private val pupilStopProgressRepository: PupilStopProgressRepository,
Expand Down Expand Up @@ -170,6 +171,7 @@ class DevDataBootstrap(
)

mapStopBootstrap.seedAllMapStops()
medalBootstrap.seedAllMedals()
val activeStops = taskBootstrap.seedAllTasks(classroom = sampleClassroom, teacher = teacher)
seedNotebookEntries(
classroom = sampleClassroom,
Expand Down
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 @@ -20,6 +20,10 @@ 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(
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,98 @@
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,
)
)
}
} 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,38 @@
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 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(nullable = false)
val awardedAt: Instant = Instant.now()
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package edu.ntnu.idi.idatt.backend.game.medals.repository

import edu.ntnu.idi.idatt.backend.game.medals.domain.Medal
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

/**
* Repository for accessing [Medal] entities.
*/
@Repository
interface MedalRepository : JpaRepository<Medal, Long> {
fun findByCode(code: String): Medal?
fun findByStopId(stopId: Long): Medal?
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package edu.ntnu.idi.idatt.backend.game.medals.repository

import edu.ntnu.idi.idatt.backend.game.medals.domain.PupilMedal
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import java.util.stream.Stream

/**
* Repository for accessing [PupilMedal] entities.
*/
@Repository
interface PupilMedalRepository : JpaRepository<PupilMedal, Long> {
fun findAllByPupilIdAndClassroomId(pupilId: Long, classroomId: Long): Stream<PupilMedal>
fun existsByPupilIdAndClassroomIdAndMedalId(pupilId: Long, classroomId: Long, medalId: Long): Boolean
}
Loading