package space.luminic.finance.services import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import space.luminic.finance.dtos.SpaceDTO import space.luminic.finance.models.NotFoundException import space.luminic.finance.models.Space import space.luminic.finance.repos.SpaceRepo @Service class SpaceServiceImpl( private val authService: AuthService, private val spaceRepo: SpaceRepo, private val categoryService: CategoryService ) : SpaceService { override fun checkSpace(spaceId: Int): Space { return getSpace(spaceId, null) } // @Cacheable(cacheNames = ["spaces"]) override fun getSpaces(): List { val user = authService.getSecurityUserId() val spaces = spaceRepo.findSpacesAvailableForUser(user) return spaces } override fun getSpace(id: Int, userId: Int?): Space { val user = userId ?: authService.getSecurityUserId() val space = spaceRepo.findSpaceById(id, user) ?: throw NotFoundException("Space with id $id not found") return space } @Transactional override fun createSpace(space: SpaceDTO.CreateSpaceDTO): Int { val user = authService.getSecurityUser() val creatingSpace = Space( name = space.name, owner = user, participants = setOf(user) ) val userId = authService.getSecurityUserId() val savedSpace = spaceRepo.create(creatingSpace, userId) if (space.createBasicCategories) { categoryService.createEtalonCategoriesForSpace(savedSpace) } return savedSpace } @Transactional override fun updateSpace( spaceId: Int, space: SpaceDTO.UpdateSpaceDTO ): Int { val userId = authService.getSecurityUserId() val existingSpace = getSpace(spaceId, null) val updatedSpace = Space( id = existingSpace.id, name = space.name, owner = existingSpace.owner, participants = existingSpace.participants, isDeleted = existingSpace.isDeleted, createdBy = existingSpace.createdBy, createdAt = existingSpace.createdAt, ) return spaceRepo.update(updatedSpace, userId) } @Transactional override fun deleteSpace(spaceId: Int) { spaceRepo.delete(spaceId) } }